Author 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"


Comments 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."


FullName 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


Installed Property 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


Keywords Property Example

This example sets the keywords for the active workbook.

ActiveWorkbook.Keywords = "Sales, West Region, 1995"


Subject 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


Title 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"


Author Property

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.


Comments Property

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.


FullName Property

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.


Installed Property

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.


Keywords Property

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.


Subject Property

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.


Title Property

Returns or sets the long, descriptive title for the object, as a string. Read-only for AddIn, read-write for Workbook.

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.


Add Method

Adds a member to a collection, as shown in the following table. Select an object for a detailed description of the Add method for that object.

Object	Description
AddIns	Adds a new add-in file to the current list of add-ins.
Arcs, Buttons, ChartObjects, Drawings, Lines, Ovals, Pictures, Rectangles, TextBoxes	Creates a new graphic object or control. The type of the object depends on the collection on which you call Add. For example, Lines.Add creates a new line; Ovals.Add creates a new oval.
CheckBoxes, DropDowns, EditBoxes, GroupBoxes, Labels, ListBoxes, OptionButtons, ScrollBars, Spinners	Creates a new control. The type of the object depends on the collection on which you call Add. For example, DropDowns.Add creates a new drop-down list box; EditBoxes.Add creates a new edit box.
Charts	Creates a new chart.
DialogSheets	Creates a new dialog sheet.
MenuBars	Creates a new menu bar.
MenuItems	Adds a new menu item to the menu. This method can also be used to restore a built-in menu item that was previously deleted.
Menus	Adds a new menu. (There is no way to create a new shortcut menu; you can only modify a built-in shortcut menu). This method can also be used to restore a built-in menu that was previously deleted.
Modules	Creates a new module.
Names	Creates a new defined name.
OLEObjects	Adds a new OLE object to the current sheet.
Scenarios	Creates a new scenario and adds it to the list of scenarios available for the current worksheet.
SeriesCollection	Adds one or more new series to the SeriesCollection collection.
Sheets	Creates a new sheet (a worksheet, chart, module, dialog sheet, or macro sheet).
Styles	Creates a new style and adds it to the list of styles available for the current workbook.
ToolbarButtons	Adds a new button to an existing toolbar.
Toolbars	Creates a new toolbar.
Trendlines	Creates a trendline with specified parameters.
Workbooks	Creates a new workbook. The new workbook becomes the active workbook.
Worksheets	Creates a new worksheet. The new worksheet becomes the active worksheet.


Add Method (AddIns Collection)

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.


Add Method (Charts Collection)

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.


Add Method (DialogSheets Collection)

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.


Add Method (MenuBars Collection)

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.


Add Method (MenuItems Collection)

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.


Add Method (Menus Collection)

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.


Add Method (Modules Collection)

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.


Add Method (Names Collection)

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).


Add Method (Scenarios Collection)

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.


Add Method (Sheets Collection)

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.


Add Method (Styles Collection)

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


Add Method (ToolbarButtons Collection)

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.


Add Method (Toolbars Collection)

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").


Add Method (Trendlines Collection)

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.


Add Method (Workbooks Collection)

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.


Add Method (Worksheets Collection)

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.


Add Method (graphic objects and controls)

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, as shown in the following illustration.


Add Method (OLEObjects Collection)

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.


Add Method (SeriesCollection Collection)

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.


Help topic not available

The Help topic cannot be displayed because Visual Basic for Applications Reference Help cannot be found or was not installed.

To install Visual Basic for Applications Reference Help

1.	Run Microsoft Office for Windows 95 Setup, and click Add/Remove.

2.	Click Microsoft Excel, and then click Change Option.

3.	Click Online Help And Samples, and then click Change Option.

4.	Make sure that the Help For Visual Basic For Microsoft Excel check box is selected.

5.	Continue with Setup.


Help topic not available

The Help topic cannot be displayed because Microsoft Excel Help cannot be found or was not installed.

To install Microsoft Excel Help

1.	Run Microsoft Office for Windows 95 Setup, and click Add/Remove.

2.	Click Microsoft Excel, and then click Change Option.

3.	Click Online Help And Samples, and then click Change Option.

4.	Make sure that the Help For Microsoft Excel check box is selected.

5.	Continue with Setup.


Help topic not available

The Help topic cannot be displayed because Data Access Objects Help cannot be found or was not installed.

To install Data Access Objects Help

1.	Run Microsoft Office for Windows 95 Setup, and click Add/Remove.

2.	Click Converters, Filters, And Data Access, and then click Change Option.

3.	Click Data Access, and then click Change Option.

4.	Make sure that the Help For Data Access Objects check box is selected.

5.	Continue with Setup.


Application Property

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.


Creator Property

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.


Parent Property

Accessor. Returns the parent object for the specified object. Read-only.


ActiveCell Property

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


ActiveMenuBar Property

Accessor. Returns a MenuBar object that represents the active menu bar. Read-only.


ActivePrinter Property

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.


ActiveSheet Property

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.


ActiveWindow Property

Accessor. Returns a Window object that represents the active window (the window on top). Read-only. Returns Nothing if no windows are open.


ActiveWorkbook Property

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.


AddIns Method

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.


AltStartupPath Property

Returns or sets a string that names the alternate startup folder. Read-write.


Arcs Method

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.


Buttons Method

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.


Calculate Method

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.


CalculateBeforeSave Property

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.


CanPlaySounds Property

True if the computer can play sound notes. Read-only.


CanRecordSounds Property

True if the computer can record sound notes. Read-only.


Caption Property

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.


CellDragAndDrop Property

True if Cell Drag And Drop editing is on. Read-write.


TransitionMenuKey Property

Returns or sets the alternate menu or help key, which is usually "/". Read-write.


TransitionNavigKeys Property

True if alternate navigation keys are active. Read-write.


Cells Method

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).


Columns Method

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.


CommandUnderlines Property

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.


ConstrainNumeric Property

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.


ConvertFormula Method

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.


CutCopyMode Property

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.


DataEntryMode Property

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.


DDEAppReturnCode Property

Returns the application-specific DDE return code that was contained in the last DDE acknowledge message received by Microsoft Excel. Read-only.


DDEExecute Method

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)


DDEInitiate Method

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.


DDEPoke Method

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.


DDERequest Method

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.


DDETerminate Method

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.


Run Method

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.


DisplayAlerts Property

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.


DisplayFormulaBar Property

True if the formula bar is displayed. Read-write.


DisplayNoteIndicator Property

True if cells containing notes display cell tips and contain note indicators (small dots in their upper-right corners). Read-write.


DisplayStatusBar Property

True if the status bar is displayed. Read-write.


DoubleClick Method

Equivalent to double-clicking the active cell.

Syntax

object.DoubleClick

object

Required. The Application object.


Evaluate Method

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.


ExecuteExcel4Macro Method

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.


FixedDecimal Property

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.


FixedDecimalPlaces Property

Returns or sets the number of fixed decimal places used when the FixedDecimal property is set to True. Read-write.


Height Property

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.


Help Method

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.


IgnoreRemoteRequests Property

True if remote DDE requests are ignored. Read-write.


InputBox Method

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.


Interactive Property

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.


International Property

Returns a 45-element array containing information about the current country and international settings. Read-only.

Syntax

object.International(index)

Elements

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.


Intersect Method

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.


Iteration Property

True if Microsoft Excel will use iteration to resolve circular references. Read-write.


Left Property

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.


 LibraryPath Property

Returns the path to the LIBRARY directory, not including the final separator. Read-only.


Lines Method

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.


MathCoprocessorAvailable Property

True if a math coprocessor is available. Read-only.


MaxChange Property

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.


MaxIterations Property

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.


MemoryFree Property

Returns the amount of memory that is still available for Microsoft Excel to use, in bytes. Read-only.


MemoryTotal Property

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.


MemoryUsed Property

Returns the amount of memory that is currently in use by Microsoft Excel, in bytes. Read-only.


MenuBars Method

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)


MouseAvailable Property

True if a mouse is available (always True on the Macintosh). Read-only.


MoveAfterReturn Property

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.


Names Method

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.


OnData Property

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.


OnEntry Property

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.


OnKey Method

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.


OnTime Method

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.


OnWindow Property

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.


OperatingSystem Property

Returns the name and version number of the current operating system. For example, "Windows 3.10" or "Macintosh 7.00". Read-only.


OrganizationName Property

Returns the registered organization name (as a string). Read-only.


Ovals Method

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.


Path Property

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).


PathSeparator Property

Returns the character ":" on the Macintosh; "\" in Windows. Read-only.


Pictures Method

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.


PreviousSelections Property

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.


Quit Method

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.


RecordRelative Property

True if macros are recorded using relative references; False if recording is absolute. Read-only.


Rectangles Method

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.


ReferenceStyle Property

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.


RegisteredFunctions Property

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.


Repeat Method

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.


Rows Method

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.


Save Method

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.


ScreenUpdating Property

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.


Selection Property

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.


SendKeys Method

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	"{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}"

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)


ShortcutMenus Method

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


StartupPath Property

Returns the complete path of the startup directory, not including the final separator. Read-only.


StatusBar Property

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.


TextBoxes Method

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.


ThisWorkbook Property

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.


Toolbars Method

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.


Top Property

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.
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).


Undo Method

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.


Union Method

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.


UsableHeight Property

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.


UsableWidth Property

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.


UserName Property

Returns or sets the name of the current user (as a string). Read-write.


Version Property

Returns the version number of Microsoft Excel. Read-only.


Wait Method

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.


Width Property

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.


Windows Method

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.


WindowsForPens Property

True if the computer is running under Microsoft Windows for Pen Computing. Read-only.


WindowState Property

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).


Workbooks Method

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.


AutoCorrect Object

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


AutoCorrect Property

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.


AutoCorrect 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


AddReplacement Method

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.


AddReplacement Method 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


CapitalizeNamesOfDays Property

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.


CapitalizeNamesOfDays Property 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


DeleteReplacement Method

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.


DeleteReplacement Method Example

This example removes the word "Temperature" from the array of AutoCorrect replacements.

With Application.AutoCorrect

.DeleteReplacement "Temperature"

End With


ReplacementList Property

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.


ReplacementList Property 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

True if text in the AutoCorrect replacements list is replaced automatically. This property is available only in Microsoft Excel for Windows 95. Read-write.


ReplaceText Property Example

This example turns off automatic text replacement.

With Application.AutoCorrect

.CapitalizeNamesOfDays = True

.ReplaceText = False

End With


TwoInitialCapitals Property

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.


TwoInitialCapitals Property 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


AxisBetweenCategories Property

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.


Crosses Property

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.


CrossesAt Property

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.


AxisGroup Property

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.


HasMajorGridlines Property

True if the axis has major gridlines. Only axes in the primary axis group can have gridlines. Read-write.


HasMinorGridlines Property

True if the axis has minor gridlines. Only axes in the primary axis group can have gridlines. Read-write.


MajorGridlines Property

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.


MajorTickMark Property

Returns or sets the type of major tick mark for the specified axis (one of xlNone, xlInside, xlOutside, or xlCross). Read-write.


MajorUnit Property

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.


MajorUnitIsAuto Property

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.


MaximumScale Property

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.


MaximumScaleIsAuto Property

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.


MinimumScale Property

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.


MinimumScaleIsAuto Property

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.


MinorGridlines Property

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.


MinorTickMark Property

Returns or sets the type of minor tick mark for the specified axis (one of xlNone, xlInside, xlOutside, or xlCross). Read-write.


MinorUnit Property

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.


MinorUnitIsAuto Property

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.


ReversePlotOrder Property

True if Microsoft Excel plots points from last to first. Read-write.

Remarks

This property is not available for radar charts.


ScaleType Property

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.


TickLabelPosition Property

Describes the position of tick labels on the specified axis (one of xlNone, xlLow, xlHigh, or xlNextToAxis). Read-write.


TickLabels Property

Accessor. Returns a TickLabels object that represents the tick labels for the specified axis. Read-only.


TickLabelSpacing Property

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.


TickMarkSpacing Property

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.


BuiltIn Property

True if the object is built-in (part of Microsoft Excel, as opposed to a custom object). Read-only.


BuiltInFace Property

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).


CopyFace Method

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).


Pushed Property

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.


Enabled Property

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.


IsGap Property

True if the button is really a gap (an extended space between buttons). Read-only.


Id Property

The button identification number of the button (built-in buttons only). Read-only.


OnAction Property

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.

Remarks

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).


PasteFace Method

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).


Font Property

Accessor. Returns a Font object that represents font of the specified object. Read-only.


Insert Method

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.


Text Property

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.

For help about using the Text worksheet function in Visual Basic, see Using Worksheet Functions in Visual Basic.


Area3DGroup Property

Accessor. Returns a ChartGroup object that represents the area chart group on a 3-D chart. Read-only.


AreaGroups Method

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.


AutoFormat Method (Chart object)

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.


AutoScaling Property

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.


Axes Method

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.


Bar3DGroup Property

Accessor. Returns a ChartGroup object that represents the bar chart group on a 3-D chart. Read-only.


BarGroups Method

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.


ChartArea Property

Accessor. Returns a ChartArea object that represents the complete chart area for the chart. Read-only.


Clear Method

Clears the entire range or chart area.

Syntax

object.Clear

object

Required. The ChartArea or Range object.


ClearContents Method

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.


Column3DGroup Property

Accessor. Returns a ChartGroup object that represents the column chart group on a 3-D chart. Read-only.


ColumnGroups Method

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.


Corners Property

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.


CreatePublisher Method

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.


DepthPercent Property

Returns or sets the depth of a 3-D chart as a percentage of the chart width (between 20 and 2000 percent). Read-write.


DoughnutGroups Method

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.


Elevation Property

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.


Floor Property

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.


GapDepth Property

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.


GapWidth Property

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.


HasAxis Property

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.


HasLegend Property

True if the chart has a legend. Read-write.


HeightPercent Property

Returns or sets the height of a 3-D chart as a percentage of the chart width (between 5 and 500 percent). Read-write.


Legend Property

Accessor. Returns a Legend object that represents the legend for the chart. Read-only.


Line3DGroup Property

Accessor. Returns a ChartGroup object that represents the line chart group on a 3-D chart. Read-only.


LineGroups Method

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.


PageSetup Property

Accessor. Returns a PageSetup object that contains all of the page setup settings for the specified object. Read-only.


Perspective Property

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.


Pie3DGroup Property

Accessor. Returns a ChartGroup object that represents the pie chart group on a 3-D chart. Read-only.


PieGroups Method

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.


PlotArea Property

Accessor. Returns a PlotArea object that represents the plot area of a chart. Read-only.


RadarGroups Method

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.


RightAngleAxes Property

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.


Rotation Property

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.


SeriesCollection Method

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.


SetDefaultChart Method

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.


Size Property

Returns or sets the size of the font. Read-write.


SubType Property

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.


SurfaceGroup Property

Accessor. Returns a ChartGroup object that represents the surface chart group of a 3-D chart. Read-only.


Type Property

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.


Walls Property

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.


XYGroups Method

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.


Activate Method

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.


Close Method

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.


Visible Property

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.


Function Property

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.


Clone Method 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 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


CreateDatabase, CreateTableDef, Append Methods 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.)

Sub createNWindEx()

Dim nWindEx As Database, customerTable As TableDef, supplierTable As TableDef

Dim dataSource As String

dataSource = _

"dBASE IV;DATABASE=C:\Program Files\Common Files\Microsoft Shared\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


Delete Method 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.)

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("C:\Program Files\Common Files\Microsoft Shared\MSquery", 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


OpenRecordset method 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


GetRows Method 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


Move Method 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


MoveNext Method 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


OpenDatabase Method 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


Seek Method 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.)

Dim db As Database, rs As Recordset

Sheets("Sheet1").Activate

Set db = OpenDatabase("C:\Program Files\Common Files\Microsoft Shared\MSquery", _

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


Update Method 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.)

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("C:\Program Files\Common Files\Microsoft Shared\MSquery", _

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


AbsolutePosition Property 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


Bookmark, Bookmarkable Properties 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

regionWanted = Application.InputBox("What state do you want data from?", _

"Specify two letters (e.g. 'WA')", Type:=2)

If regionWanted = False Then	' user cancelled InputBox

Exit Sub

End If

criteria = "[REGION] = '" & regionWanted & "'"

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


Connect, SourceTableName Properties 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.

Dim nWindEx As Database, tDef As TableDef

Dim dataSource As String

dataSource = _

"dBASE IV;DATABASE=C:\Program Files\Common Files\Microsoft Shared\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


Count Property 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


DateCreated, LastUpdated Properties 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


EditMode Property 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


Filter Property 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


LockEdits Property 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


Name Property 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


NoMatch Property 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


PercentPosition Property 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


RecordCount Property 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


Size, Type Properties 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.)

Dim db As Database, recordsToCopy As Recordset, tDef As Recordset

Dim fieldsToStore(1000), fileName As String

fileName = "ORDDTAIL.DBF"

Set db = _

Workspaces(0).OpenDatabase("C:\Program Files\Common Files\Microsoft Shared\MSquery", _

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


Sort Property 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


CreateQueryDef method, SQL Property 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


Updatable Property 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


ArrowHeadLength Property

Returns or sets the length of the arrow head (one of xlShort, xlMedium, or xlLong). Read-write.


ArrowHeadStyle Property

Returns or sets the arrow head type (one of xlNone, xlOpen, xlClosed, xlDoubleOpen, or xlDoubleClosed). Read-write.


ArrowHeadWidth Property

Returns or sets the arrow head width (one of xlNarrow, xlMedium, xlWide). Read-write.


AutoSize Property

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).


AutoText Property

True if the object automatically generates appropriate text based on context. Read-write.


Border Property

Accessor. Returns a Border object that represents the border of the object. Read-only.


BottomRightCell Property

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.


BringToFront Method

Brings the object to the front of the z-order.

Syntax

object.BringToFront

object

Required. The object to which this method applies.


Characters Method

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.


Chart Property

Accessor. Returns a Chart object that represents the chart contained in the object. Read-only.


ClearFormats Method

Clears the formatting of the object.

Syntax

object.ClearFormats

object

Required. The object to which this method applies.


Color Property

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.


Delete Method

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.


Index Property

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.


LineStyle Property

Returns or sets the line style of the border. Read-write.

For Range object borders, this property can have one of the following values:

For drawing object borders, this property can have one of the following values:


LockedText Property

True if the text in the object will be locked to prevent changes when the document is protected. Read-write.


NumberFormatLinked Property

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.


Placement Property

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.


PrintObject Property

True if the object will be printed when the document is printed. Read-write.


Reshape Method

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.


RoundedCorners Property

True if the drawing object has rounded corners. Read-write.


SendToBack Method

Sends the object to the back of the z-order.

Syntax

object.SendToBack

object

Required. The object to which this method applies.


ShowLegendKey Property

True if the data label legend key is visible. Read-write.


TopLeftCell Property

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.


Vertices Property

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.


Weight Property

Returns or sets the weight of the border (one of xlHairline, xlThin, xlMedium, or xlThick). Read-write.


ZOrder Property

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).


AddressLocal Method

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.


CategoryLocal Property

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.


DisplayScrollBars Property

True if scroll bars are visible for all workbooks. Read-write.


FormulaLocal Property

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.


FormulaR1C1 Property

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.


FormulaR1C1Local Property

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.


HasDataLabels Property

True if the series has data labels. Read-write.


PhoneticAccelerator Property

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.


RefersToLocal Property

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.


RefersToR1C1 Property

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.


RefersToR1C1Local Property

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.


SortSpecial Method

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).


SourceData Property

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.


ShortcutMenus Method 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


StartupPath Property Example

This example displays the full path to the Microsoft Excel startup folder.

MsgBox Application.StartupPath


StatusBar 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


TextBoxes Method 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


ThisWorkbook Property Example

This example closes the workbook that contains the example code. Changes to the workbook, if any, are not saved.

ThisWorkbook.Close savechanges:=False


Toolbars Method 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 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


Undo Method Example

This example cancels the last user interface action. The example must be the first line in a macro.

Application.Undo


Union 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()"


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


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


UserName Property Example

This example displays the current user name.

MsgBox "Current user is " & Application.UserName


Version Property 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 & "!"


Wait Method 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


Width 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


Windows Method 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 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 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


Workbooks Method 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


AxisBetweenCategories Property Example

This example causes the value axis in Chart1 to cross the category axis between categories.

Charts("Chart1").Axes(xlCategory).AxisBetweenCategories = True


Crosses 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 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


AxisGroup Property 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


HasMajorGridlines 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 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


MajorGridlines 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	'set color to blue

End If

End With


MajorTickMark 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 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 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


MaximumScale 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 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


MinimumScale 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 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 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	'set color to blue

End If

End With


MinorTickMark 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 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 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


ReversePlotOrder Property Example

This example reverses the order in which points on the value axis in Chart1 are plotted.

Charts("Chart1").Axes(xlValue).ReversePlotOrder = True


ScaleType Property Example

This example sets the value axis in Chart1 to use a logarithmic scale.

Charts("Chart1").Axes(xlValue).ScaleType = xlLogarithmic


TickLabelPosition 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 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 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 Example

This example sets the number of categories between tick marks on the category axis in Chart1.

Charts("Chart1").Axes(xlCategory).TickMarkSpacing = 10


BuiltIn 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


BuiltInFace Property 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


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


Enabled 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


Id Property 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


IsGap Property 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"


OnAction 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 = ""


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


Pushed 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


Font Property 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


Insert Method 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


Text Property 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


Area3DGroup Property 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 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


AutoFormat Method 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"


AutoScaling Property 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


Axes Method 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


Bar3DGroup Property 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 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


ChartArea Property 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


Clear 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


ClearContents Method 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


Column3DGroup Property Example

This example sets the subtype for the 3-D column chart group in Chart1.

Charts("Chart1").Column3DGroup.SubType = 4


ColumnGroups Method Example

This example sets the subtype for column chart group one in Chart1.

Charts("Chart1").ColumnGroups(1).SubType = 3


Corners Property 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


 CreatePublisher Method Example

This example creates a publisher based on cells A1:A20 on Sheet1.

Worksheets("Sheet1").Range("A1:A20").CreatePublisher "stock data"


DepthPercent 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


DoughnutGroups Method Example

This example sets the starting angle for doughnut group one in Chart1.

Charts("Chart1").DoughnutGroups(1).FirstSliceAngle = 45


Elevation 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


Floor Property 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


GapDepth Property 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 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


HasAxis Property Example

This example turns on the primary value axis for Chart1.

Charts("Chart1").HasAxis(xlValue, xlPrimary) = True


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


HeightPercent 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


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


Line3DGroup 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


LineGroups Method 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


PageSetup Property Example

This example sets the center header text for Chart1.

Charts("Chart1").PageSetup.CenterHeader = "December Sales"


Perspective 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


Pie3DGroup Property 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 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


PlotArea Property Example

This example sets the color of the plot area interior of Chart1 to cyan.

Charts("Chart1").PlotArea.Interior.ColorIndex = 8


RadarGroups Method 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


RightAngleAxes 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


Rotation 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


SeriesCollection Method Example

This example turns on data labels for series one in Chart1.

Charts("Chart1").SeriesCollection(1).HasDataLabels = True


SetDefaultChart Method Example

This example sets the default chart template to the custom autoformat named "Monthly Sales."

Application.SetDefaultChart formatName:="Monthly Sales"


Size Property 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


SubType Property 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


SurfaceGroup Property 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


Type 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


Walls Property 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


XYGroups Method 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


Activate 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


Close Method 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


Visible Property 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()"


Function Property 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


ArrowHeadLength 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 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 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


AutoSize Property 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 Example

This example sets the data labels for series one in Chart1 to automatically generate appropriate text.

Charts("Chart1").SeriesCollection(1).DataLabels.AutoText = True


Border Property 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


BottomRightCell 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 Example

This example brings rectangle one on Sheet1 to the front of the z-order.

Worksheets("Sheet1").Rectangles(1).BringToFront


Characters Method 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


Chart Property 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


ClearFormats 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


Color Property 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)


Delete Method 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


Index Property 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


LineStyle Property 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


LockedText Property Example

This example locks the text on button one on Sheet1.

Worksheets("Sheet1").Buttons(1).LockedText = True


NumberFormatLinked Property 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


Placement Property 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


PrintObject Property Example

This example sets line one on Sheet1 to print with the worksheet.

Worksheets("Sheet1").Lines(1).PrintObject = True


Reshape Method 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


RoundedCorners Property Example

This example adds rounded corners to rectangle one on Sheet1.

Worksheets("Sheet1").Rectangles(1).RoundedCorners = True


SendToBack Method Example

This example sends rectangle one on Sheet1 to the back of the z-order.

Worksheets("Sheet1").Rectangles(1).SendToBack


ShowLegendKey Property 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


TopLeftCell 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


Vertices Property 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


Weight Property Example

This example sets the border weight for oval one on Sheet1.

Worksheets("Sheet1").Ovals(1).Border.Weight = xlMedium


ZOrder Property 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


AddressLocal 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)


CategoryLocal 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


DisplayScrollBars Property Example

This example turns off scroll bars for all workbooks.

Application.DisplayScrollBars = False


FormulaLocal 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 Example

This example sets the formula for cell B1 on Sheet1.

Worksheets("Sheet1").Range("B1").FormulaR1C1 = "=SQRT(R1C1)"


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(Z1S1:Z10S1) in a message box.

MsgBox Worksheets(1).Range("A11").FormulaR1C1Local


HasDataLabels 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


PhoneticAccelerator 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


 RefersToLocal 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 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 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


SortSpecial Method 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


SourceData Property Example

Assume that you used an external data source to create a pivot table 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


Add Method 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 Example

This example creates an empty chart sheet and inserts it before the active sheet.

ActiveWorkbook.Charts.Add


Add Method 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 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 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 Example

This example adds a new menu to the worksheet menu bar.

MenuBars(xlWorksheet).Menus.Add caption:="More Help"


Add Method Example

This example inserts a new Visual Basic module before the active sheet.

ActiveWorkbook.Modules.Add


Add Method 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 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 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 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 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 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 Example

This example creates a new linear trendline in Chart1.

ActiveWorkbook.Charts("Chart1").SeriesCollection(1).Trendlines.Add


Add Method Example

This example creates a new workbook.

Workbooks.Add


Add Method 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)


Add 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 Example

This example creates a new Microsoft Word OLE object on Sheet1.

ActiveWorkbook.Worksheets("Sheet1").OLEObjects.Add _

classType:="Word.Document.6"


Add 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")


Background Property 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


Bold Property Example

This example sets the font to bold for the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").Font.Bold = True


Italic Property Example

This example sets the font to italic for the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").Font.Italic = True


Outline Property Example

This example sets the outline on Sheet1 to use automatic styles.

Worksheets("Sheet1").Outline.AutomaticStyles = True


Strikethrough Property Example

This example sets the font in the active cell on Sheet1 to strikethrough.

Worksheets("Sheet1").Activate

ActiveCell.Font.Strikethrough = True


Underline Property Example

This example sets the font in the active cell on Sheet1 to single underline.

Worksheets("Sheet1").Activate

ActiveCell.Font.Underline = xlSingle


LargeScroll Method Example

This example scrolls the active window of Sheet1 down three pages.

Worksheets("Sheet1").Activate

ActiveWindow.LargeScroll down:=3


SmallScroll Method Example

This example scrolls the active window of Sheet1 down three rows.

Worksheets("Sheet1").Activate

ActiveWindow.SmallScroll down:=3


DownBars 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


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


FirstSliceAngle Property 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


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


HasHiLoLines 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


HasRadarAxisLabels 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


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


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


HiLoLines 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


Overlap 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


RadarAxisLabels 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


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


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


VaryByCategories Property 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


Add 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 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 Example

This example creates a drop-down list box on Sheet1.

With Worksheets("Sheet1").DropDowns.Add(10, 10, 120, 18)

.DropDownLines = 10

End With


AddVertex 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


CentimetersToPoints Method Example

This example sets the left margin of Sheet1 to 5 centimeters.

Worksheets("Sheet1").PageSetup.LeftMargin = _

Application.CentimetersToPoints(5)


ChartObjects 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


CircularReference Property Example

This example selects the first cell in the first circular reference on Sheet1.

Worksheets("Sheet1").CircularReference.Select


ColorButtons Property Example

This example turns off colored toolbar buttons.

Application.ColorButtons = False


ColorIndex 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


DataLabels Method 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


Explosion Property 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


GetOpenFilename 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 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


GridlineColorIndex Property Example

This example sets the active window gridline color to blue.

ActiveWindow.GridlineColorIndex = 5


InchesToPoints Method Example

This example sets the left margin of Sheet1 to 2.5 inches.

Worksheets("Sheet1").PageSetup.LeftMargin = _

Application.InchesToPoints(2.5)


LinkCombo Method Example

This example links list box one and edit box two on Dialog1.

DialogSheets("Dialog1").DrawingObjects( _

Array("List Box 1", "Edit Box 2")).LinkCombo


MarkerBackgroundColor 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 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 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 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


OnRepeat 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"


OnSheetActivate Property 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 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 = ""


OnUndo 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"


OutlineFont Property Example

This example sets the font for cell A1 on Sheet1 to an outline font.

Worksheets("Sheet1").Range("A1").Font.OutlineFont = True


PatternColor 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 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


ResetTipWizard Method Example

This example resets the TipWizard and then enables it.

With Application

.ResetTipWizard

.EnableTipWizard = True

End With


ToolbarButtons Method Example

This example deletes the New Workbook button from the Standard toolbar.

Application.Toolbars("Standard").ToolbarButtons(1).Delete


Volatile Method 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


ActivateMicrosoftApp Method Example

This example starts and activates Word.

Application.ActivateMicrosoftApp xlMicrosoftWord


ActivateNext Method Example

This example sends the active window to the back of the z-order.

ActiveWindow.ActivateNext


ActivatePrevious Method Example

This example activates the window at the back of the z-order.

ActiveWindow.ActivatePrevious


AddIndent 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


AxisTitle 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


CategoryNames 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")


ChartTitle Property Example

This example sets the text for the title of Chart1.

With Charts("Chart1")

.HasTitle = True

.ChartTitle.Text = "First Quarter Sales"

End With


Deselect Method 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


Display3DShading Property Example

This example sets check box one on Sheet1 to use 3-D shading.

Worksheets("Sheet1").CheckBoxes(1).Display3DShading = True


DoughnutHoleSize Property 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


EnableCancelKey Property 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


EndStyle Property 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


MultiSelect Property Example

This example sets list box one on Dialog1 to allow extended multiple selections.

DialogSheets("Dialog1").ListBoxes(1).MultiSelect = xlExtended


NavigateArrow Method 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


OpenText 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


RegisterXLL Method Example

This example loads an XLL file and registers the functions and commands in the file.

Application.RegisterXLL "XLMAPI.XLL"


SaveCopyAs 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"


Selected 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


UpdateFromFile Method Example

This example updates the active workbook.

ActiveWorkbook.UpdateFromFile


XValues Property 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)


BCCRecipients 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


CCRecipients 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


Enclosures 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


Mailer 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


Received 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


SendDateTime 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 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


SendMailer Method 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


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


ForwardMailer Method Example

This example forwards the active workbook.

ActiveWorkbook.ForwardMailer


HasMailer Property 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


HasRoutingSlip 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


Reply 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 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


Route 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 Example

This example sends the workbook to the next recipient.

If ActiveWorkbook.HasRoutingSlip And _

Not ActiveWorkbook.Routed Then

ActiveWorkbook.Route

End If


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


SendMail Method Example

This example sends the active workbook to a single recipient.

ActiveWorkbook.SendMail recipients:="Jean Selva"


AutomaticStyles Property Example

This example sets the outline on Sheet1 to use automatic styles.

Worksheets("Sheet1").Outline.AutomaticStyles = True


ShowLevels Method 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


SummaryColumn Property 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 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


BottomMargin 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"


CenterFooter 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 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 Example

This example centers Sheet1 horizontally when the worksheet is printed.

Worksheets("Sheet1").PageSetup.CenterHorizontally = True


CenterVertically Property Example

This example centers Sheet1 vertically when the worksheet is printed.

Worksheets("Sheet1").PageSetup.CenterVertically = True


ChartSize Property Example

This example scales the first chart in the active workbook to fit a full page.

ActiveWorkbook.Charts(1).PageSetup.ChartSize = xlFullPage


FirstPageNumber Property Example

This example sets the first page number of Sheet1 to 100.

Worksheets("Sheet1").PageSetup.FirstPageNumber = 100


FitToPagesTall Property 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 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


LeftFooter Property Example

This example prints the page number in the lower-left corner of every page.

Worksheets("Sheet1").PageSetup.LeftFooter = "&P"


LeftHeader Property Example

This example prints the date in the upper-left corner of every page.

Worksheets("Sheet1").PageSetup.LeftHeader = "&D"


LeftMargin 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"


Order Property 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


PaperSize Property Example

This example sets the paper size of Sheet1 to legal.

Worksheets("Sheet1").PageSetup.PaperSize = xlPaperLegal


PrintGridlines Property Example

This example prints cell gridlines when Sheet1 is printed.

Worksheets("Sheet1").PageSetup.PrintGridlines = True


PrintHeadings Property Example

This example turns off heading printing for Sheet1.

Worksheets("Sheet1").PageSetup.PrintHeadings = False


RightFooter Property Example

This example prints the page number in the lower-right corner of every page.

Worksheets("Sheet1").PageSetup.RightFooter = "&P"


RightHeader Property Example

This example prints the filename in the upper-right corner of every page.

Worksheets("Sheet1").PageSetup.RightHeader = "&F"


RightMargin Property 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"


TopMargin Property 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"


Zoom Property Example

This example scales Sheet1 by 150 percent when the worksheet is printed.

Worksheets("Sheet1").PageSetup.Zoom = 150


Application 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


Creator 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


Parent Property Example

This example displays the name of the chart that contains myAxis.

Set myAxis = Charts(1).Axes(xlValue)

MsgBox myAxis.Parent.Name


AddCustomList Method Example

This example adds an array of strings as a custom list.

Application.AddCustomList Array("cogs", "sprockets", _

"widgets", "gizmos")


AlertBeforeOverwriting Property Example

This example causes an alert to be displayed before nonblank cells are overwritten during drag-and-drop editing.

Application.AlertBeforeOverwriting = True


ClipboardFormats Property 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


DeleteCustomList Method Example

This example deletes a custom list.

n = Application.GetCustomListNum(Array("cogs", "sprockets", _

"widgets", "gizmos"))

Application.DeleteCustomList n


EnableTipWizard Property Example

This example enables the TipWizard.

Application.EnableTipWizard = True


FileConverters Property 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


GetCustomListContents 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 Example

This example deletes a custom list.

n = Application.GetCustomListNum(Array("cogs", "sprockets", _

"widgets", "gizmos"))

Application.DeleteCustomList n


EditDirectlyInCell Property Example

This example enables editing in cells.

Application.EditDirectlyInCell = True


MailLogoff Method Example

This example closes the established mail session if there is one.

If Not IsNull(Application.MailSession) Then Application.MailLogoff


MailLogon 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 Example

This example closes the established mail session if there is one.

If Not IsNull(Application.MailSession) Then Application.MailLogoff


MailSystem Property 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


NextLetter Method Example

This example opens the oldest unread Microsoft Excel letter from the In Tray.

If Application.MailSystem = xlPowerTalk Then _

Application.NextLetter


OnCalculate Property 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 = ""


PromptForSummaryInfo Property Example

This example displays a prompt that asks for summary information when files are first saved.

Application.PromptForSummaryInfo = True


SheetsInNewWorkbook Property 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"


StandardFont 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 Example

This example sets the standard font size to 12 points.

Application.StandardFontSize = 12


AutoFilter 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"


DisplayHorizontalScrollBar Property Example

This example turns on the horizontal scroll bar for the active window.

ActiveWindow.DisplayHorizontalScrollBar = True


DisplayVerticalScrollBar Property Example

This example turns on the vertical scroll bar for the active window.

ActiveWindow.DisplayVerticalScrollBar = True


DisplayWorkbookTabs Property Example

This example turns on the workbook tabs.

ActiveWindow.DisplayWorkbookTabs = True


Draft Property Example

This example turns off graphics printing for Sheet1.

Worksheets("Sheet1").PageSetup.Draft = True


FilterMode Property 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


FontStyle 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 Example

This example sets the footer margin of Sheet1 to 0.5 inch.

Worksheets("Sheet1").PageSetup.FooterMargin = _

Application.InchesToPoints(0.5)


HeaderMargin Property Example

This example sets the header margin of Sheet1 to 0.5 inch.

Worksheets("Sheet1").PageSetup.HeaderMargin = _

Application.InchesToPoints(0.5)


PrintNotes Property Example

This example turns off notes printing.

Worksheets("Sheet1").PageSetup.PrintNotes = False


PrintQuality Property 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)


ScrollColumn Property Example

This example moves column three to the left of the window.

Worksheets("Sheet1").Activate

ActiveWindow.ScrollColumn = 3


ScrollRow Property Example

This example moves row 10 to the top of the window.

Worksheets("Sheet1").Activate

ActiveWindow.ScrollRow = 10


ScrollWorkbookTabs Method Example

This example scrolls the workbook tabs to the last sheet in the workbook.

ActiveWindow.ScrollWorkbookTabs position:=xlLast


Shadow Property Example

This example adds a shadow to the title of Chart1.

Charts("Chart1").ChartTitle.Shadow = True


Subscript Property Example

This example makes the second character in cell A1 a subscript.

Worksheets("Sheet1").Range("A1").Characters(2, 1).Font.Subscript = True


Superscript 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


TabRatio Property Example

This example makes the workbook tabs half the width of the horizontal scroll bar.

ActiveWindow.TabRatio = 0.5


Charts 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


ClearArrows Method Example

This example clears tracer arrows on Sheet1.

Worksheets("Sheet1").ClearArrows


Copy 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")


DrawingObjects Method 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


GroupObjects Method Example

This example ungroups the graphic objects in group one on Sheet1.

Worksheets("Sheet1").GroupObjects(1).Ungroup


Move Method Example

This example moves Sheet1 after Sheet3 in the active workbook.

Worksheets("Sheet1").Move _

after:=Worksheets("Sheet3")


OnDoubleClick Property 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 = ""


PrintOut Method Example

This example prints the active sheet.

ActiveSheet.PrintOut


PrintPreview Method Example

This example displays a print preview of Sheet1.

Worksheets("Sheet1").PrintPreview


Protect Method Example

This example protects the active workbook.

ActiveWorkbook.Protect password := "drowssap"


ProtectContents Property 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 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


Scenarios Method Example

This example sets the comment for the first scenario on Sheet1.

Worksheets("Sheet1").Scenarios(1).Comment = _

"Worst-case July 1993 sales"


Unprotect Method Example

This example removes protection from the active workbook.

ActiveWorkbook.Unprotect


AskToUpdateLinks Property Example

This example causes Microsoft Excel to ask the user to update links when a file that contains links is opened.

Application.AskToUpdateLinks = True


AutoUpdate Property 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


Backward 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


BlackAndWhite Property Example

This example causes Sheet1 to print in black and white.

Worksheets("Sheet1").PageSetup.BlackAndWhite = True


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


ChangeFileAccess Method Example

This example sets the active workbook to read-only.

ActiveWorkbook.ChangeFileAccess Mode:=xlReadOnly


ChartGroups Method 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


Checked Property 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


CopyObjectsWithCells Property Example

This example causes Microsoft Excel to cut, copy, extract, and sort drawing objects with cells.

Application.CopyObjectsWithCells = True


Count Property 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


CustomListCount Property Example

This example displays the number of custom lists currently defined.

MsgBox "There are currently " & Application.CustomListCount & _

" defined custom lists."


DefaultFilePath Property Example

This example displays the current default file path.

MsgBox "The current default file path is " & _

Application.DefaultFilePath


Dialogs Method Example

This example displays the dialog box for the Open command on the File menu.

Application.Dialogs(xlDialogOpen).Show


DisplayBlanksAs Property Example

This example causes Microsoft Excel not to plot blank cells in Chart1.

Charts("Chart1").DisplayBlanksAs = xlNotPlotted


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


DisplayFullScreen Property Example

This example causes Microsoft Excel to display in full-screen mode.

Application.DisplayFullScreen = True


DisplayExcel4Menus Property 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


DisplayRecentFiles Property Example

This example turns off the list of most recently used files.

Application.DisplayRecentFiles = False


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


Duplicate Method Example

This example duplicates oval one on Sheet1 and then selects the copy.

Set dOval = Worksheets("Sheet1").Ovals(1).Duplicate

dOval.Select


Edit Method 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


FindFile Method Example

This example displays the Open dialog box.

Application.FindFile


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


HasTitle 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


InsertFile Method 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"


Intercept 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 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


LargeButtons Property Example

This example displays the large toolbar buttons.

Application.LargeButtons = True


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


MenuItems 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 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


NameIsAuto Property 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


Object Property 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


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


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


Pattern Property Example

This example adds a crisscross pattern to the interior of cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Interior.Pattern = xlCrissCross


Period 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


PlotVisibleOnly Property Example

This example causes Microsoft Excel to plot only visible cells in Chart1.

Charts("Chart1").PlotVisibleOnly = True


PrintArea Property 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


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


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


VisibleRange Property Example

This example displays the number of cells visible on Sheet1.

Worksheets("Sheet1").Activate

MsgBox "There are " & Windows(1).VisibleRange.Cells.Count _

& " cells visible"


RefersTo 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


ShowDetail Property 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


TransitionMenuKeyAction 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


Update Method Example

This example updates the link to OLE object one on Sheet1.

Worksheets("Sheet1").OLEObjects(1).Update


Verb Method Example

This example sends the default verb to the server for OLE object one on Sheet1.

Worksheets("Sheet1").OLEObjects(1).Verb


WallsAndGridlines2D Property Example

This example causes Microsoft Excel to draw 2-D gridlines on Chart1.

Charts("Chart1").WallsAndGridlines2D = True


AddMenu Method 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"


AdvancedFilter Method Example

This example filters a database (named "Database") based on a criteria range named "Criteria."

Range("Database").AdvancedFilter _

action:=xlFilterInPlace, _

criteriaRange:=Range("Criteria")


CheckSpelling Method Example

This example checks the spelling on Sheet1.

Worksheets("Sheet1").CheckSpelling


Colors 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


DisplayRightToLeft Property Example

This example sets window one to display right-to-left.

ActiveWorkbook.Windows(1).DisplayRightToLeft = True


FillAcrossSheets Method 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")


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


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


Range 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


RecordMacro Method Example

This example records either Visual Basic code or an XLM formula.

Application.RecordMacro basicCode:="Application.Run ""MySub"" ", _

xlmCode:="=MySub()"


Show Method 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 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


Value 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


Accelerator Property 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


ActiveChart Property Example

This example turns on the legend for the active chart.

ActiveChart.HasLegend = True


ActiveDialog Property Example

This example sets the height of the active dialog box.

ActiveDialog.DialogFrame.Height = 91


AddChartAutoFormat Method Example

This example adds a new autoformat based on Chart1.

Application.AddChartAutoFormat _

chart:=Charts("Chart1"), name:="Presentation Chart"


AddFields 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")


AddItem 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


AutoFilterMode 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


AutoOutline 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


BorderAround Method 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


CancelButton Property Example

This example sets the CancelButton property for button one on Dialog1.

DialogSheets("Dialog1").Buttons(1).CancelButton = True


ChangeLink Method Example

This example changes a Microsoft Excel link.

ActiveWorkbook.ChangeLink "c:\excel\book1.xls", _

"c:\excel\book2.xls", xlExcelLinks


ChartWizard Method 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"


CheckBoxes Method 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


ClearOutline Method Example

This example clears the outline for the range A1:G37 on Sheet1.

Worksheets("Sheet1").Range("A1:G37").ClearOutline


ConsolidationFunction 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 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 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


DefaultButton 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


DeleteChartAutoFormat Method Example

This example deletes the custom autoformat named "Presentation Chart".

Application.DeleteChartAutoFormat name:="Presentation Chart"


DialogFrame Property 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


DismissButton Property Example

This example sets the DismissButton property for every button on Dialog1.

For Each bt in DialogSheets("Dialog1").Buttons

bt.DismissButton = True

Next bt


DisplayClipboardWindow Property Example

This example displays the Clipboard window.

Application.DisplayClipboardWindow = True


DisplayInfoWindow Property Example

This example displays the Info window.

Application.DisplayInfoWindow = True


DropDownLines Property Example

This example sets the number of list lines in drop-down list box one on Dialog1.

DialogSheets("Dialog1").DropDowns(1).DropDownLines = 10


DropDowns Method Example

This example sets the number of list lines in drop-down list box one on Dialog1.

DialogSheets("Dialog1").DropDowns(1).DropDownLines = 10


EditBoxes Method Example

This example sets the text in edit box one on Dialog1.

DialogSheets("Dialog1").EditBoxes(1).Text = "Start here"


Extend Method 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")


Focus Property 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


GroupBoxes Method Example

This example sets the title for group box one on Dialog1.

DialogSheets("Dialog1").GroupBoxes.Text = "Choose one"


HelpButton Property 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


Hide Method Example

This example hides the active dialog box.

ActiveDialog.Hide


InputType Property Example

This example sets edit box one on Dialog1 to require an integer.

DialogSheets("Dialog1").EditBoxes(1).InputType = xlInteger


Labels Method Example

This example sets the text for label one on Dialog1.

DialogSheets("Sheet1").Labels(1).Text = "Search results"


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


LegendEntries Method Example

This example sets the font for legend entry one on Chart1.

Charts("Chart1").Legend.LegendEntries(1).Font.Name = "Arial"


LegendKey Property 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


LinkedCell Property 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 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 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


LinkSources Method 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


List Property 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"


ListBoxes Method 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 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 Example

This example fills list box one with the range A1:A10 on Sheet1.

DialogSheets("Dialog1").Listboxes(1).ListFillRange = _

"Sheet1!A1:A10"


ListIndex Property Example

This example selects item four in list box one on Dialog1.

DialogSheets("Dialog1").ListBoxes(1).ListIndex = 4


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


Merge Method Example

This example merges the styles from the workbook TEMPLATE.XLS into the active workbook.

ActiveWorkbook.Styles.Merge Workbook:=Workbooks("TEMPLATE.XLS")


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


MultiLine Property Example

This example enables multiline input for edit box one on Dialog1.

DialogSheets("Dialog1").EditBoxes(1).MultiLine = True


OpenLinks Method 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)


OptionButtons Method Example

This example sets option button one on Dialog1.

Dialogsheets("Dialog1").OptionButtons(1).Value = xlOn


ActiveCell Property 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


ActiveMenuBar Property Example

This example displays the name (Caption property) of the active menu bar.

MsgBox "The active menu bar is called " & ActiveMenuBar.Caption


ActivePrinter Property Example

This example displays the name of the active printer.

MsgBox "The name of the active printer is " & Application.ActivePrinter


ActiveSheet Property Example

This example displays the name (Name property) of the active sheet.

MsgBox "The name of the active sheet is " & ActiveSheet.Name


ActiveWindow Property Example

This example displays the name (Caption property) of the active window.

MsgBox "The name of the active window is " & ActiveWindow.Caption


ActiveWorkbook Property Example

This example displays the name (Name property) of the active workbook.

MsgBox "The name of the active workbook is " & ActiveWorkbook.Name


AddIns Method 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


TransitionMenuKey Property Example

This example sets the transition menu key to "/" (which is the default).

Application.TransitionMenuKey = "/"


TransitionNavigKeys Property 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


AltStartupPath Property 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"


Arcs Method 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


Buttons Method 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 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 Example

This example causes workbooks to be calculated before they are saved to disk.

Application.Calculation = xlManual

Application.CalculateBeforeSave = True


CanPlaySounds 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 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


Caption 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


CellDragAndDrop Property Example

This example turns on the Cell Drag And Drop editing option.

Application.CellDragAndDrop = True


ProtectScenarios Property 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."


RemoveAllItems Method Example

This example removes all entries from list box one on Dialog1.

DialogSheets("Dialog1").Listboxes(1).RemoveAllItems


RemoveItem Method Example

This example removes the first entry from list box one on Dialog1.

DialogSheets("Dialog1").Listboxes(1).RemoveItem index:=1


ScrollBars Method 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


SetInfoDisplay Method 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 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"


ShortcutKey Property 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"


ShowToolTips Property Example

This example causes Microsoft Excel to display ToolTips.

Application.ShowToolTips = True


SizeWithWindow Property Example

This example sets Chart1 to be sized to its window.

Charts("Chart1").SizeWithWindow = True


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


Spinners Method 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


TextToColumns 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


UpdateLink Method Example

This example updates all links in the active workbook.

ActiveWorkbook.UpdateLink name:=ActiveWorkbook.LinkSources


Paste Method (Chart 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 (Pictures Object) 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) 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) 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


Paste Method (Worksheet Object) 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")


PasteSpecial Method (Range 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


PasteSpecial Method 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


ApplyDataLabels Method Example

This example applies category labels to series one in Chart1.

Charts("Chart1").SeriesCollection(1).ApplyDataLabels type:=xlShowLabel


DataLabel 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


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


MarkerStyle Property 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


PictureType 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 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


BaseField Property 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 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"


Calculation 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"


ChildField Property 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 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


CurrentPage Property 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"


DataRange Property 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


DataType Property 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


Group 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)


GroupLevel Property 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


HiddenItems 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


LabelRange Property 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


Orientation Property 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


ParentField Property 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


ParentItems 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


PivotItems 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


Position Property 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


Subtotals Property 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)


TotalLevels Property 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."


Ungroup Method 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


VisibleItems 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


ParentItem Property 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


ParentShowDetail Property 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


SourceName Property 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)


LocationInTable Property 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


PivotTable Property 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"


PivotField Property 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


PivotItem Property 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


ColumnFields 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 Example

This example sets the PivotTable to show column grand totals.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable

pvtTable.ColumnGrand = True


ColumnRange Property Example

This example selects the column headers for the PivotTable.

Worksheets("Sheet1").Activate

Range("A3").Select

ActiveCell.PivotTable.ColumnRange.Select


DataBodyRange Property Example

This example selects the active PivotTable data.

Worksheets("Sheet1").Activate

Range("A3").Select

ActiveCell.PivotTable.DataBodyRange.Select


DataFields 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


DataLabelRange Property Example

This example selects the data field labels in the PivotTable.

Worksheets("Sheet1").Activate

Range("A3").Select

ActiveCell.PivotTable.DataLabelRange.Select


HasAutoFormat Property 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


HiddenFields 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


InnerDetail 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


PageFields 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 Example

This example selects the PivotTable page headers.

Worksheets("Sheet1").Activate

Range("A3").Select

ActiveCell.PivotTable.PageRange.Select


PivotFields 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


RefreshDate Property 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 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 Example

This example refreshes the PivotTable.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable

pvtTable.RefreshTable


RowFields 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 Example

This example sets the PivotTable to show row grand totals.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable

pvtTable.RowGrand = True


RowRange Property Example

This example selects the PivotTable row headers.

Worksheets("Sheet1").Activate

Range("A3").Select

ActiveCell.PivotTable.RowRange.Select


SaveData Property Example

This example sets the PivotTable to save data with the workbook.

Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable

pvtTable.SaveData = True


ShowPages Method 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"


TableRange1 Property Example

This example selects the PivotTable, except that its page fields are not selected.

Worksheets("Sheet1").Activate

Range("A3").PivotTable.TableRange1.Select


TableRange2 Property Example

This example selects the PivotTable, including its page fields.

Worksheets("Sheet1").Activate

Range("A3").PivotTable.TableRange2.Select


VisibleFields 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


PivotTables 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 Example

This example creates a new PivotTable from a Microsoft Excel database (contained in the range A1:C100).

ActiveSheet.PivotTableWizard xlDatabase, Range("A1:C100")


Address 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]


ApplyNames Method Example

This example applies names to the entire sheet.

Cells.ApplyNames names:=Array("Sales", "Profits")


ApplyOutlineStyles Method Example

The following example applies automatic outlining styles to the selection. The selection must include the entire outline range on a worksheet.

Selection.ApplyOutlineStyles


Areas 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


AutoFill Method 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


AutoFormat Method Example

This example formats cells A1:D8 on Sheet1, using a predefined format.

Worksheets("Sheet1").Range("A1:D8").AutoFormat format:=xlClassic1


AutoFit Method 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


ClearNotes Method Example

This example clears all notes and sound notes in columns A through C on Sheet1.

Worksheets("Sheet1").Columns("A:C").ClearNotes


Column Property 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


ColumnDifferences 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


ColumnWidth Property Example

This example doubles the width of column A on Sheet1.

With Worksheets("Sheet1").Columns("A")

.ColumnWidth = .ColumnWidth * 2

End With


Consolidate Method 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


CreateNames 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


CurrentArray 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


CurrentRegion 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


DataSeries Method 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


Dependents Property Example

This example selects the dependents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate

Range("A1").Dependents.Select


DialogBox Method 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


DirectDependents Property Example

This example selects the direct dependents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate

Range("A1").DirectDependents.Select


DirectPrecedents Property Example

This example selects the direct precedents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate

Range("A1").DirectPrecedents.Select


End Method 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


EntireColumn 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 Example

This example selects the entire row that contains the active cell. The example must be run from a worksheet.

ActiveCell.EntireRow.Select


FillDown 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 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 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 Example

This example fills the range A1:A10 on Sheet1, based on the contents of cell A10.

Worksheets("Sheet1").Range("A1:A10").FillUp


Find 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


FindNext 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 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


FormulaArray 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 Example

This example hides the formulas in column A on Sheet1 when the worksheet is protected.

Worksheets("Sheet1").Columns("A").FormulaHidden = True


GoalSeek Method 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")


Goto 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


Cells 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


Columns 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


CommandUnderlines Property Example

This example turns off command underlines in Microsoft Excel for the Macintosh.

Application.CommandUnderlines = xlOff


ConstrainNumeric Property 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


ConvertFormula Method 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)


CutCopyMode Property 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


DataEntryMode Property 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


DDEAppReturnCode Property Example

This example sets the variable appErrorCode to the DDE return code.

appErrorCode = Application.DDEAppReturnCode


DDEExecute 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


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


DDEPoke Method 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 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 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


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


HasArray 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


HasFormula Property 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


Hidden Property Example

This example hides column C on Sheet1.

Worksheets("Sheet1").Columns("C").Hidden = True


Justify Method Example

This example justifies text in cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Justify


ListNames Method 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


Next 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


NoteText Method Example

This example sets the cell note text for cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").NoteText "This may change!"


NumberFormatLocal 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


Offset 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


OutlineLevel Property Example

This example sets the outline level for row two on Sheet1.

Worksheets("Sheet1").Rows(2).OutlineLevel = 1


PageBreak Property 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


Parse Method 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")


Precedents Property Example

This example selects the precedents of cell A1 on Sheet1.

Worksheets("Sheet1").Activate

Range("A1").Precedents.Select


PrefixCharacter Property Example

This example displays the prefix character for cell A1 on Sheet1.

MsgBox "The prefix character is " & _

Worksheets("Sheet1").Range("A1").PrefixCharacter


Previous 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


Replace 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


Resize Method 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


Row Property 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 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


RowHeight Property Example

This example doubles the height of row one on Sheet1.

With Worksheets("Sheet1").Rows(1)

.RowHeight = .RowHeight * 2

End With


Select Method Example

This example selects cells A1:B3 on Sheet1.

Worksheets("Sheet1").Activate

Range("A1:B3").Select


SoundNote Property 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


Style Property 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


SubscribeTo Method Example

This example subscribes to the "stock data" publisher.

Worksheets("Sheet1").Range("D1").SubscribeTo "stock data"


Summary Property 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


Table Method 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


UseStandardHeight Property Example

This example sets the height of row one on Sheet1 to the standard height.

Worksheets("Sheet1").Rows(1).UseStandardHeight = True


UseStandardWidth Property Example

This example sets the width of column A on Sheet1 to the standard width.

Worksheets("Sheet1").Columns("A").UseStandardWidth = True


VerticalAlignment 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


Worksheet Property 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


WrapText Property 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


Borders Method 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


CopyPicture 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")


Cut Method Example

This example cuts the range A1:G37 on Sheet1 and places it on the Clipboard.

Worksheets("Sheet1").Range("A1:G37").Cut


Formula Property Example

This example sets the formula for cell A1 on Sheet1.

Worksheets("Sheet1").Range("A1").Formula = "=$A$4+$A$10"


 FunctionWizard Method Example

This example starts the Function Wizard for the active cell on Sheet1.

Worksheets("Sheet1").Activate

ActiveCell.FunctionWizard


HorizontalAlignment Property Example

This example applies left alignment to the range A1:A5 on Sheet1.

Worksheets("Sheet1").Range("A1:A5").HorizontalAlignment = xlLeft


Interior Property Example

This example sets the interior color for cell A1 onSheet1 to cyan.

Worksheets("Sheet1").Range("A1").Interior.ColorIndex = 8


Locked Property 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


NumberFormat 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)"


RemoveSubtotal 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


ShowDependents 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


ShowErrors 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


ShowPrecedents 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


Sort Method 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


Subtotal 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)


Delivery 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


Message 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


Recipients 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?"

.ReturnWhenDone = True

End With

Workbooks("BOOK1.XLS").Route


Reset Method 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


ReturnWhenDone Property 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


Status Property 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


TrackStatus Property 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


ChangeScenario Method 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 Example

This example selects the changing cells for scenario one on Sheet1.

Worksheets("Sheet1").Activate

ActiveSheet.Scenarios(1).ChangingCells.Select


Comment Property Example

This example sets the comment for scenario one on Sheet1.

Worksheets("Sheet1").Scenarios(1).Comment = _

"Worst case July 1993 sales"


CreateSummary Method 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")


ErrorBar Method 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 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


HasErrorBars 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


InvertIfNegative Property 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


PlotOrder Property 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


Points Method Example

This example applies a data label to point one in series one in Chart1.

Charts("Chart1").SeriesCollection(1).Points(1).ApplyDataLabels


Smooth Property 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


Trendlines Method Example

This example adds a linear trendline to series one in Chart1.

Charts("Chart1").SeriesCollection(1).Trendlines.Add Type:=xlLinear


Values Property 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)


Import 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"


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


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


SQLBind 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 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 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 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 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 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 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 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 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


IncludeAlignment 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 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 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 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 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 Example

This example sets the style attached to cell A1 on Sheet1 to include protection format.

Worksheets("Sheet1").Range("A1").Style.IncludeProtection = True


Using Worksheet Functions in Visual Basic Example

This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Notice 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 program.

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")


Cell Error Values 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


HelpContextID 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 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


DisplayAlerts Property 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


DisplayFormulaBar Property Example

This example hides the formula bar.

Application.DisplayFormulaBar = False


DisplayNoteIndicator Property Example

This example hides the note indicators.

Application.DisplayNoteIndicator = True


DisplayStatusBar 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


DoubleClick Method Example

This example double-clicks the active cell on Sheet1.

Worksheets("Sheet1").Activate

Application.DoubleClick


Evaluate Method Example

This example turns on bold formatting in cell A1 on Sheet1.

Worksheets("Sheet1").Activate

boldCell = "A1"

Application.Evaluate(boldCell).Font.Bold = True


ExecuteExcel4Macro 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)")


FixedDecimal 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 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


Height 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


Help Method Example

This example displays the contents screen for the Help file OTISAPP.HLP.

Application.Help "OTISAPP.HLP"


IgnoreRemoteRequests Property Example

This example sets the IgnoreRemoteRequests property to True so that remote DDE requests are ignored.

Application.IgnoreRemoteRequests = True


InputBox Method 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)


Interactive Property 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


ActivePane 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


Arrange Method Example

This example tiles all the windows in the application.

Application.Windows.Arrange arrangeStyle:=xlTiled


DisplayAutomaticPageBreaks Property Example

This example causes Sheet1 to display automatic page breaks.

Worksheets("Sheet1").DisplayAutomaticPageBreaks = True


DisplayFormulas Property Example

This example changes the active window in BOOK1.XLS to display formulas.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate

ActiveWindow.DisplayFormulas = True


DisplayGridlines Property 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 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


DisplayOutline Property Example

This example displays outline symbols for the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate

ActiveWindow.DisplayOutline = True


DisplayZeros Property Example

This example sets the active window in BOOK1.XLS to display zero values.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate

ActiveWindow.DisplayZeros = True


FreezePanes Property Example

This example freezes split panes in the active window in BOOK1.XLS.

Workbooks("BOOK1.XLS").Worksheets("Sheet1").Activate

ActiveWindow.FreezePanes = True


GridlineColor 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)


Panes Method 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


SelectedSheets Method 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


Split Property 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 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 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 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 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


CreateBackup Property 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


DialogSheets Method 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


Excel4IntlMacroSheets 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 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."


FileFormat Property 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


HasPassword Property 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


Modules Method 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"


NewWindow Method Example

This example creates a new window for the active workbook.

ActiveWorkbook.NewWindow


Open Method Example

This example opens the workbook ANALYSIS.XLS and then runs its Auto_Open macro.

Workbooks.Open "ANALYSIS.XLS"

ActiveWorkbook.RunAutoMacros xlAutoOpen


ProtectStructure Property 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 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


ReadOnly Property 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 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


RunAutoMacros Method 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


SaveAs Method 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


Saved Property 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


Sheets 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


Styles Method Example

This example deletes the user-defined style "Stock Quote Style" from the active workbook.

ActiveWorkbook.Styles("Stock Quote Style").Delete


Worksheets Method 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"


WriteReserved 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 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


TransitionExpEval Property Example

This example causes Microsoft Excel to use Lotus 1-2-3 expression evaluation rules for Sheet1.

Worksheets("Sheet1").TransitionExpEval = True


TransitionFormEntry Property Example

This example causes Microsoft Excel to use Lotus 1-2-3 formula entry rules for Sheet1.

Worksheets("Sheet1").TransitionFormEntry = True


Date1904 Property Example

This example causes Microsoft Excel to use the 1904 date system for the active workbook.

ActiveWorkbook.Date1904 = True


DeleteNumberFormat Method Example

This example deletes the number format "000-00-0000" from the active workbook.

ActiveWorkbook.DeleteNumberFormat("000-00-0000")


DisplayDrawingObjects Property Example

This example hides all the drawing objects in the active workbook.

ActiveWorkbook.DisplayDrawingObjects = xlHide


Drawings Method Example

This example brings drawing one to the front of Sheet1.

Worksheets("Sheet1").Drawings(1).BringToFront


PrecisionAsDisplayed Property Example

This example causes calculations on the active workbook to use only the precision of the numbers as they are displayed.

ActiveWorkbook.PrecisionAsDisplayed = True


SaveLinkValues Property Example

This example causes Microsoft Excel to save external link values with the active workbook.

ActiveWorkbook.SaveLinkValues = True


ShowDataForm Method Example

This example displays the data form for Sheet1.

Worksheets(1).ShowDataForm


SpecialCells Method Example

This example selects the last cell in the used range of Sheet1.

Worksheets("Sheet1").Activate

ActiveSheet.Cells.SpecialCells(xlLastCell).Activate


StandardHeight 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 Example

This example sets the width of column one on Sheet1 to the standard width.

Worksheets("Sheet1").Columns(1).ColumnWidth = _

Worksheets("Sheet1").StandardWidth


UpdateRemoteReferences Property Example

This example causes remote references to be updated on the active workbook.

ActiveWorkbook.UpdateRemoteReferences = True


UsedRange Property Example

This example selects the used range on Sheet1.

Worksheets("Sheet1").Activate

ActiveSheet.UsedRange.Select


WindowNumber 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


Array Function Example (Microsoft Excel)

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


Chr Function Example (Microsoft Excel)

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


CVErr Function Example (Microsoft Excel)

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


Do...Loop Statement Example (Microsoft Excel)

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


For Each...Next Statement Example (Microsoft Excel)

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 Example (Microsoft Excel)

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


If...Then...Else Statement Example (Microsoft Excel)

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


Is Operator Example (Microsoft Excel)

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


IsEmpty Function Example (Microsoft Excel)

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


IsNull Function Example (Microsoft Excel)

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


LBound Function Example (Microsoft Excel)

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


Like Operator Example (Microsoft Excel)

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


Mod Operator Example (Microsoft Excel)

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


RGB Function Example (Microsoft Excel)

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


Select Case Statement Example (Microsoft Excel)

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


Set Statement Example (Microsoft Excel)

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


Static Statement Example (Microsoft Excel)

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")


TypeName Function Example (Microsoft Excel)

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 Example (Microsoft Excel)

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


With Statement Example (Microsoft Excel)

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


SolverAdd 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 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 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 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 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 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 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 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 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 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")


SolverSave 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 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")


SolverReset Function 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")


International Property Example

This example displays the international decimal separator.

MsgBox "The decimal separator is " & _

Application.International(xlDecimalSeparator)


Intersect 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


Iteration Property Example

This example sets the Iteration property to True, so that circular references are resolved by iteration.

Application.Iteration = True


Left 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


LibraryPath Property 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


Lines Method 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


MathCoprocessorAvailable Property 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


MaxChange Property Example

This example sets the maximum change for each iteration to 0.1.

Application.MaxChange = 0.1


MaxIterations Property Example

This example sets the maximum number of iterations to 1000.

Application.MaxIterations = 1000


MemoryFree Property Example

This example displays a message box showing the number of free bytes.

MsgBox "Microsoft Excel has " & Application.MemoryFree & " bytes free"


MemoryTotal 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 Example

This example displays a message box showing the number of bytes currently being used.

MsgBox "Microsoft Excel is currently using " & _

Application.MemoryUsed & " bytes"


MenuBars Method 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"


MouseAvailable Property 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


MoveAfterReturn Property Example

This example sets the MoveAfterReturn property to True.

Application.MoveAfterReturn = True


Names Method 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


OnData Property 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 = ""


OnEntry 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 = ""


OnKey Method 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}", ""


OnTime Method 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


OnWindow Property 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 = ""


OperatingSystem Property Example

This example displays the name of the operating system.

MsgBox "Microsoft Excel is using " & Application.OperatingSystem


OrganizationName Property Example

This example displays the registered organization name.

MsgBox "The registered organization is " & Application.OrganizationName


Ovals Method 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


Path Property Example

This example displays the complete path to Microsoft Excel.

MsgBox "The path is " & Application.Path


PathSeparator Property Example

This example displays the current path separator.

MsgBox "The path separator character is " & Application.PathSeparator


Pictures Method 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


PreviousSelections Property 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"


Quit Method Example

This example saves all open workbooks and then closes Microsoft Excel.

For Each w In Application.Workbooks

w.Save

Next w

Application.Quit


RecordRelative Property 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


Rectangles Method 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


ReferenceStyle Property 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


RegisteredFunctions Property 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


Repeat Method Example

This example repeats the last user interface command. The example must be the first line in a macro.

Application.Repeat


Rows 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


Save Method 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


ScreenUpdating Property 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."


Selection 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)


SendKeys Method Example

This example uses the SendKeys method to quit Microsoft Excel for Windows.

Application.SendKeys("%fx")


Background Property

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.


Bold Property

True if the font is bold. Read-write.


Italic Property

True if the font is italic. Read-write.


Outline Property

Accessor. Returns an Outline object that represents the outline for the specified worksheet.


Strikethrough Property

True if the font is struck through. Read-write.


Underline Property

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.


Using arrays in Visual Basic

You can use an array variable when you need to work with a group of related values. For example, if you have a figure for daily expenses for each day of the year, rather than declaring 365 variables, you would declare one array variable with 365 elements. Each element in an array contains one value. The following statement declares the array variable expense with 365 elements (the default index for the first element is 0).

Dim expense(364) as Currency

To set the value of an element, you specify the element's index. The following example assigns each element in the array an initial value of 20.

Sub FillArray()

Dim expense(364) As Currency

Dim counter As Integer

For counter = 0 to 364

expense(counter) = 20

Next

End Sub

Changing the lower bound

By default, the first element in an array has the index 0 (zero). You can use the Option Base statement at the top of a module to change the default index of the first element to 1. The following example declares the array variable expense with 365 elements (the default index for the first element is 1).

Option Base 1

Dim expense(365) As Currency

Tip   Because the indexes of the objects in collections are 1-based, you may find it useful to always include the statement Option Base 1 at the top of modules that use arrays and collections together.

You can also explicitly set the lower bound of an array by using a To clause, as shown in the following examples.

Dim expense(1 To 365) As Currency

Dim weekday(7 To 13) As String

Storing Variant values in arrays

There are two ways to create arrays of Variant values. One way is to declare an array of the Variant data type, as shown in the following example.

Option Base 1

Sub ArrayVar()

Dim myData(4) As Variant

myData(1) = "Claudia Bendel"

myData(2) = "4242 Maple Blvd"

myData(3) = 38

myData(4) = Format("06-09-1952", "General Date")

End Sub

The other way is to assign the array returned by the Array function to a Variant variable, as shown in the following example.

Option Base 1

Sub VarArray()

Dim myData As Variant

myData = Array("Claudia Bendel", "4242 Maple Blvd", 38, _

Format("06-09-1952", "General Date"))

End Sub

Note that you identify the elements in an array of Variant values by index, no matter which technique you use to create the array. For example, the following statement could be added to either of the preceding two examples.

MsgBox myData(1) & " data recorded."

Important   When creating arrays of Variant values, remember that each element uses 16 bytes of memory. For more information, see Saving space when creating arrays.

Moving values between arrays and cells

You can use an array to work with a series of values on a worksheet. Using For...Next loops, you can efficiently assign values in cells to elements in an array, and vice versa, as shown in the following example. The FillArray procedure fills a string array with the values from cells A1:A12 on Sheet1. The FillCells procedure places the values from this array in cells A1:L1 on Sheet2.

Dim myArray(1 To 12) As String

Sub FillArray()

For x = 1 To 12

myArray(x) = Worksheets("Sheet1").Cells(x, 1).Value

Next

End Sub

Sub FillCells()

For x = 1 To 12

Worksheets("Sheet2").Cells(1, x).Value = myArray(x)

Next

End Sub

Using multidimensional arrays

In Visual Basic, you can declare arrays with up to 60 dimensions. For example, the following statement declares a two-dimensional, 5-by-10 array.

Dim multi(1 To 5, 1 To 10) As Single

Use nested For...Next statements to process multidimensional arrays. The following procedure fills a two-dimensional array with the Single values in cells A1:J5 on Sheet1.

Sub FillMulti()

Dim i, j As Integer

Dim multi(1 To 5, 1 To 10) As Single

For i = 1 To 5

For j = 1 To 10

multi(i, j) = Worksheets("Sheet1").Cells(i, j).Value

Next j

Next i

End Sub

More Examples

For more examples of using arrays in Visual Basic, see Samples.xls in the Examples folder.


 Declaring resizable arrays in Visual Basic

If you don't know exactly how large to make an array and you want to be able to change its size while the code is running, you can declare a dynamic array. To do this, use the Static, Dim, Private, or Public statement to declare an array but leave the parentheses empty, as shown in the following example.

Dim newArray() As Single

Later, in a procedure within the array's scope, use the ReDim statement to change the number of dimensions and to define the number of elements and the upper and lower bounds for each dimension. You can use the ReDim statement to change the dynamic array as often as you need to.

The following example finds the current region (the range, bounded by empty cells, that contains the active cell) on Sheet1. It then counts the rows and columns and uses the results to define the upper bound of each dimension in the dynamic array myArray.

Dim myArray()

Sub FindBounds()

Dim myRange As Range

Set myRange = Worksheets("Sheet1").Range("A1").CurrentRegion

r = myRange.Rows.Count

c = myRange.Columns.Count

ReDim myArray(1 To r, 1 To c)

End Sub

Preserving values in dynamic arrays

Each time you use the ReDim statement, all the values stored in the array are lost. If you want to retain the existing data, you can use the Preserve keyword. For example, the following statement enlarges the array myArray by 10 elements without losing the current values of the original elements.

ReDim Preserve myArray(UBound(myArray) + 10)

Notes

•	Using the Preserve keyword, you can change only the upper bound of the last dimension in a dynamic array.

•	If you use the Preserve keyword with a dynamic array, you cannot change the number of dimensions.


Saving space when creating arrays

Unless you specify a data type, arrays contain Variant values. Each element in a Variant array occupies 16 bytes of memory. By specifying a data type for the elements in an array, you can reduce the amount of memory that the array requires.

' Integer array uses 20 bytes (10 elements * 2 bytes).

Option Base 1

Dim myIntegerArray(10) As Integer

' Double-precision array uses 80 bytes (10 elements * 8 bytes).

Option Base 1

Dim myDoubleArray(10) As Double

' Variant array uses at least 160 bytes (10 elements * 16 bytes).

Option Base 1

Dim myVariantArray(10) As Variant

For information about how much memory each element in an array of a given data type requires, see Data Type Summary.

The maximum number of elements an array can contain varies depending on the amount of available memory. You are not likely to encounter this limit, but using arrays that exceed the amount of random-access memory available on your system can slow down your code, because the data must be read from and written to disk.


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 Word, PowerPoint, or Microsoft Project. You can communicate with other applications by using OLE Automation or dynamic data exchange (DDE).

Tip   For detailed information about using OLE Automation and DDE to control applications from Microsoft Excel, see the following books published by Microsoft Press:

•	Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide (Microsoft Press, 1995), ISBN 1-55615-819-X

•	Developing Microsoft Excel Solutions, 2nd ed., by Eric Wells (Microsoft Press, 1995), ISBN 1-55615-893-9

These and other titles are available wherever computer books are sold and directly from Microsoft Press. Credit card orders: 1-800-MSPRESS (1-800-677-7377). CompuServe: GO MSP. To request a catalog of current Microsoft Press publications, call 1-800-MSPRESS.

OLE Automation

OLE Automation allows you to retrieve, edit, and export data by referencing another application's objects, properties, and methods. Application objects that can be referenced by another application are called OLE Automation objects.

To exchange data with another application using OLE Automation from Microsoft Excel, you first obtain a reference to the application you want to communicate with by using CreateObject or GetObject. Then, using the objects, properties, and methods of the other application, you add, change, or delete information. When you finish making your changes, close the application.

For information about referencing an object library and using the objects it exposes, see OLE Automation.

Dynamic data exchange (DDE)

Dynamic data exchange (DDE) is a protocol that permits two applications to communicate by continuously and automatically exchanging data through a DDE "channel." Many applications that don't yet support OLE Automation support DDE. To control a DDE conversation between two applications, you establish a channel, select a topic, request and send data, and then close the channel. The following table lists the tasks that Microsoft Excel performs with DDE and the methods used to control each task in Visual Basic.

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
More examples

For more examples of communication with other applications using OLE and DDE, see Samples.xls in the Examples folder.


Retrieving external data

Using the objects, methods, and properties of the Data Access Objects (DAO) library, you can open a database, design and run a query to extract a set of records, and return data to your Microsoft Excel workbook.

To use DAO, you must first create a reference from your workbook to the DAO library. To create this reference, activate a Visual Basic module, click References on the Tools menu, and then select Microsoft DAO 3.0 Object Library in the Available References box.

Use the OpenDatabase method to connect to a database and open it. After opening the database, use the OpenRecordset method to access a table or query for results. To navigate through the recordset, use the Move method. To find a specific record, use the Seek method.

If you need only a subset of records instead of the entire recordset, use the CreateQueryDef method to design a customized query to select records that meet your criteria.

When you've created the recordset you want, you can copy it from the database to your workbook using the CopyFromRecordset method in Microsoft Excel.

When you finish working with a database, it's a good idea to close it using the Close method, to save memory.

For more information about using the Data Access Objects library to retrieve external data, see the following topics:

Data Access Objects Overview

Using Data Access

Retrieving Data Using SQLand DAO

Accessing External Databases with DAO

Accessing Data in ODBC Databases with DAO

More examples

For more examples of retrieving external data, see Samples.xls in the Examples folder.


Writing code for international use

During installation, Microsoft Excel registers the English object libraries as the default libraries, regardless of the language version of Microsoft Excel itself. However, if you install the appropriate Visual Basic object library in your Windows system folder and install 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 Microsoft Excel because the object library translates your code into statements that can run in any language version of Microsoft Excel.

To choose a code language

1.	Activate a Visual Basic module, and then click Options on the Tools menu.

2.	Click the Module General tab.

3.	Click Default Settings.

4.	In the Language/Country box, select the language and country you want to use.

Visual Basic uses the operating system locale settings to interpret and display numbers, dates, and currency figures entered in dialog boxes and worksheet cells. The operating system locale setting can be different from the code language setting specified on the Module General tab in Microsoft Excel.

To choose an operating system locale

1.	On the Start menu in Windows 95, click Settings, and then click Control Panel.

2.	Double-click Regional Settings.

3.	On the Regional Settings tab, select the international setting you want to use.

Use the following guidelines to write Visual Basic code that runs most 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 (using the English/United States setting on the Module General tab). The code will run on any computer running Microsoft Excel, because Microsoft Excel registers the English object libraries as the default during installation.

•	Write your code in any localized language, and distribute the code with the correct object library file. 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 Object library filenames.

•	Write your code in any localized language, and distribute the code without the object library file for that language. The code will only run on computers with the proper object library file already installed. For a complete list of languages and their corresponding object libraries, see Object library filenames.

Note   Don't write Visual Basic code for distribution to other computers using the English/(Custom) setting on the Module General Tab. Code written in that environment won't run properly on other computers.


Object library filenames

Unless your Visual Basic code is written in English, you should always include the appropriate object libraries for the language your code is written in when you distribute your application, in case the recipients don't already have them installed. The following table lists the most common object library filenames.

Language	Microsoft Excel for Windows 95	Visual Basic for Applications
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 (Portugal)	XL5PTG32.OLB	VBAPTG32.OLB
Portuguese (Brazil)	XL5PTB32.OLB	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
The object library files for any language can be downloaded from CompuServe. After you connect to CompuServe, go to the Microsoft Software Library (GO MSL), search for the keyword "object" or "library," and then download the files you need.


Checking your code for language errors

By default, Visual Basic checks your code for syntax errors as you type in a module. While syntax checking is on, an incorrectly written line of code will turn red after you press ENTER.

To turn syntax checking on or off

1.	On the Tools menu, click Options.

2.	On the Module General tab, select or clear the Display Syntax Errors check box.

Common causes of syntax errors

The following are some of the more common causes of syntax errors:

•	You omit quotation marks before or after a string.

•	You omit a list separator or comma within a list of arguments.

•	You use parentheses with a method when you shouldn't.

•	You misspell a keyword.

•	You omit the End statement from a control structure (for example, End If after a multiple-line If...Then...Else statement).

Avoiding other common errors

Some errors are not identified as syntax errors. Instead, they appear as errors when Visual Basic tries to compile or run your code. Still other errors appear only as unexpected results or behavior in an otherwise correct procedure. The following are some simple steps you can take while writing your procedures to avoid some of these mistakes:

•	Check for misspelled accessor methods or properties. A very common mistake is to forget the "s" at the end of an accessor method such as Workbooks or Worksheets. Because Workbook and Worksheet are valid keywords, Visual Basic will not recognize them as syntax errors; however, they will cause an error when you try to run your procedure.

•	Check your code for misspelled words. If you don't use the Option Explicit statement at the top of your module, a misspelled word will be interpreted as a new variable. This may not create an error, but your code may produce unexpected results.

For more information about debugging, see How to use the Debug window.


Using MsgBox for simple error checking

You can use the MsgBox function, which displays a built-in Visual Basic dialog box, to stop your code and check for errors. When a message box is displayed, the procedure is temporarily halted. When the user clicks a button in the message box, the procedure continues. While writing and testing your procedure, you can use this message box to display the value of a variable or expression at any point in the code.

For example, you can insert a message box into a looping statement to check a value each time the loop repeats its statement block.

Sub CheckLoop()

num = 10

Do While num > 5

square = num ^ 2

MsgBox "The squared value is " & square

num = num - 1

Loop

End Sub

Notice that when you use the MsgBox function to display information, you can ignore the return value and therefore omit the parentheses. Just type MsgBox and then the string or variable you want to display. Use an ampersand (&) to connect a string to a variable name or expression.

Tip   If your code produces an endless loop and contains the MsgBox function, you may need to comment out the line that contains the MsgBox function.

For more information about debugging, see How to use the Debug window.


Naming conflict errors

A naming conflict occurs when you try to create an identifier that Visual Basic recognizes as having been previously defined. In some cases, naming conflicts generate errors such as "Ambiguous name detected" or "Duplicate declaration in current scope." In other cases, naming conflicts go unnoticed and result in bugs and erroneous results.

You can avoid most naming conflicts by understanding the scoping characteristics of identifiers for data, objects, and procedures. Visual Basic has three scoping levels: procedure, private, and public. A naming conflict can occur when an identifier is visible at more than one scoping level or has two different meanings at the same level.

For example, procedures in different modules can have the same name. Therefore, a procedure named "MySub" can be defined in two modules named "Mod1" and "Mod2." No conflicts will occur if each procedures is called only within its own module. However, an error can occur if "MySub" is called from a third module and no qualification is provided to distinguish between the two "MySub" procedures.

Most naming conflicts can be resolved by preceding each identifier with a qualifier that consists of the qualifying module name and, if necessary, a qualifying workbook name. The following example uses the value of a check box on a worksheet to determine which procedure named "Report" to run from the workbook named "Sales96.xls": the procedure in the module named "Quarterly" or the one in the module named "Yearly."

If Worksheets("Options").CheckBoxes("ShowQuarters").Value = xlOn Then

[Sales96.xls].Quarterly.Report

Else

[Sales96.xls].Yearly.Report

End If

You can use any combination of qualifiers that is sufficient to differentiate between matching identifiers.

Tips

•	Typical errors caused by naming conflicts include those for ambiguous names, duplicate declarations, undeclared identifiers, and procedures that are not found.

•	By beginning each module with the Option Explicit statement, you can avoid some potential naming conflicts and identifier-related bugs by forcing explicit declarations of variables before they are used.

For more information about debugging, see How to use the Debug window.


Error trapping

You can use the On Error GoTo statement to trap errors and direct procedure flow to the location of error-handling statements within a procedure. For example, the following statement directs the flow to the myErrorCheck label.

On Error GoTo myErrorCheck

You can place the Exit Sub statement in front of the myErrorCheck label so that the procedure doesn't run the error-checking statements if no errors occur.

Exit Sub

myErrorCheck:

MsgBox "Error number " & Err & ": " & Error(Err)

Resume Next

End Sub

The Err function returns the number corresponding to the most recent run-time error. It acts like any public variable that contains an integer. The Error function returns the corresponding message text for a given error number.

For a list of Visual Basic errors you can handle with error-handling statements, see Trappable Errors. For more information about setting error traps and writing error-handling statements, see the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide.

For more information about debugging, see How to use the Debug window.

More examples

For more examples of error trapping, see Samples.xls in the Examples folder.


Tips for debugging

By "debugging" your code, you can find and resolve errors in it. There are three types of errors you may encounter as you run a macro:

•	Language errors occur when Visual Basic tries to compile incorrectly constructed code. An example of a language error is a Next statement without a corresponding For statement. Language errors include syntax errors, which are errors in Visual Basic "grammar." These include misspelled keywords, incorrectly used parentheses (especially around arguments to methods), or omitted list separators or quotation marks.

•	Run-time errors occur after the macro starts to run. Examples of run-time errors include attempting an illegal operation, such as writing to a file that doesn't exist or dividing by 0 (zero).

•	Logical errors occur when the macro runs successfully but doesn't perform as you intended or produces incorrect results. To find these errors, you need to use the Debug window to step through your macro or break into it while it's running so that you can check the values and the flow.

For more information about the basics of debugging, see How to use the Debug window.

General debugging tips

•	When you write your macro, break it into many small Sub and Function procedures that have specific, well-defined purposes.

•	Include comments to remind yourself of the purpose of procedures or particular lines of code.

•	Use the Option Explicit statement at the top of your module. This requires you to declare all variables. An error occurs when Visual Basic discovers a variable that has not been explicitly declared. This is an easy way to find misspelled variable names.

•	Use the macro recorder to determine which Visual Basic objects, methods, and properties you need to use in your code. For more information, see Recording a macro to generate code.

•	Press CTRL+G to display the Debug window.

•	Use the Immediate pane of the Debug window to test individual lines of code, run procedures, or change values after the macro halts.

•	In your procedure, type Debug.Print followed by an expression to display the expression value in the Immediate pane of the Debug window when the statement runs.

•	For information about setting watch expressions that continually monitor the value of a variable or expression as you step through your code, see How to use the Debug window.

•	Use MsgBox to stop your code and display values or expressions in a built-in dialog box. For more information, see Using MsgBox for simple error checking.

•	When you find an error, use the Find and Replace commands (Edit menu) to check other procedures or modules for similar errors.

•	To reset variables and restart execution from the beginning, click Reset on the Run menu.

•	You can print a module (some users find it easier to read code on paper than on the screen). Switch to the module, and then click  [image].

•	While in break mode, select a variable or expression, and then click  [image]  to see its value.

Entering break mode

•	To stop an endless loop, press ESC or CTRL+BREAK. While debugging an endless loop, you may need to comment out any statements that display message boxes.

•	Click  [image]  to set breakpoints to halt execution of code at certain statements. Click the line of code, and then click  [image]  again to remove a breakpoint.

•	When adding or editing a watch expression, select either the Break When Value Is True or Break When Value Changes check box in either the Add Watch or Edit Watch dialog box (Tools menu). Watch expressions are displayed in the Watch pane of the Debug window.

•	To have a macro automatically enter break mode each time it runs, include a Stop statement after the statements you want to debug.

•	To set Visual Basic to break for each error, click Options on the Tools menu. On the Module General tab, select the Break On All Errors check box.

Stepping through your macro

•	Instead of clicking  [image]  to run your macro, click  [image]  to run each statement in each procedure, one at a time, in the Debug window. Click  [image]  to run a called procedure in one step.

•	After entering break mode anywhere in your macro, you can step through the remainder of the macro in the Debug window by clicking  [image]  or  [image].

Tracing procedures

•	While you're stepping through your macro, the name of the active procedure appears at the top of the Debug window.

•	To see a list of all the currently active procedure calls, click  [image]  in the Debug window.

Naming conflicts

Naming conflicts can produce errors such as "Ambiguous name detected" or "Duplicate declaration in current scope." A naming conflict can occur when an identifier is visible at more than one scoping level or has two different meanings at the same scoping level.

For information about defining the scope of your variables, constants, and procedures, see Understanding scope and Scoping levels.


Scoping levels

Visual Basic has three scoping levels that determine where and when variable name is recognized (visible), as described in the following table.

Scope	Visible in	Declared with	Referenced as
Procedure	One procedure only	Dim or Static, declared inside a procedure	variable
Private	All procedures in the module	Dim or Private, declared at the top of the module before all procedures	[module.]variable
Public	All procedures in all modules in the workbook, and in all referencing workbooks	Public, declared at the top of the module before all procedures	[workbook.[module.]]variable


Adding controls to a sheet

You can place controls on a worksheet, chart sheet, or dialog sheet.

1.	On the View menu, click Toolbars.

2.	In the Toolbars box, select the Forms check box, and then click OK.

The Forms toolbar is displayed.

3.	On the Forms toolbar, click the button for the control you want to add, and then drag on the sheet until the control is the size and shape you want.

If Microsoft Excel beeps when you click a button on the Forms toolbar, that control is not available for the active sheet type.

4.	Change the default label of the control, if it has one, to indicate the purpose of the control. For example, you might change "Check Box 4" to "Show Subtotals."

5.	In the name box at the left end of the formula bar, change the default name of the control to a meaningful name that's easy for you to remember. For example, you might change "Check Box 4" to "Subtotal_ckbox."

This is the name you'll need to specify whenever you want to work with the control in Visual Basic code, so the easier it is to remember, the easier your programming will be.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Linking controls to a cell or range

You can link the value of a check box, option button, list box, scroll bar, or spinner to a cell on a worksheet. You can also link the data for a list box or drop-down list box to a range on a worksheet. Neither of these procedures requires you to create a Visual Basic procedure.

To link the value of a control to a cell

1.	Select the control.

2.	Click  [image].

3.	Click in the Cell Link box.

4.	Switch to the worksheet that contains the cell you want to link to the control, and then click the cell.

The cell reference is automatically entered in the Cell Link box. The workbook that contains the linked cell must be open for the link to work.

Tip   To link the value of the control to more than one cell, link the control to one cell, and then reference that cell in the remaining cells you want to link the control to.

You can also link a control to a cell by using the LinkedCell property in a Visual Basic procedure. The following example links a check box on Dialog1 to cell A1 on Sheet1.

Sub SetLink()

DialogSheets("Dialog1").CheckBoxes("Check Box 1") _

.LinkedCell = "Sheet1!A1"

End Sub

Note that while a dialog box is displayed, if you change the value of a control linked to a cell on a worksheet, the value of the cell changes immediately. Canceling the dialog box does not return the cell to its original value (the value it had before the dialog box was displayed). Instead, the value remains changed.

To fill a list box or drop-down list box with data from a range

1.	Select the list box or drop-down list box.

2.	Click  [image].

3.	Click in the Input Range box.

4.	Switch to the worksheet that contains the range you want to link the list box to, and then select the range.

The range reference is automatically entered in the Input Range box. The workbook that contains the worksheet must be open for the input range to work.

You can also set the input range for a list box by using the ListFillRange property in a Visual Basic procedure. The following example sets the input range for a list box on Dialog1 to A1:A5 on Sheet1 in the active workbook.

Sub SetRange()

DialogSheets("Dialog1").ListBoxes("List Box 1") _

.ListFillRange = "Sheet1!A1:A5"

End Sub

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Initializing controls in a custom dialog box

When you run your custom dialog box, you usually initialize the controls to a set of default conditions. You do this by associating a procedure with the OnAction property of the dialog frame.

In the initializing procedure, use the ActiveDialog property to access the methods and properties of the dialog box that's open. In the following example, the text in the edit box is set to an empty string, the focus is set to Edit Box 1, and the option buttons are cleared.

Sub Initialize()

With ActiveDialog

.EditBoxes("Edit Box 1").Text = ""

.Focus = "Edit Box 1"

End With

For Each b In ActiveDialog.OptionButtons

b.Value = xlOff

Next

End Sub

To associate an initializing procedure with a custom dialog box

Microsoft Excel runs the procedure assigned to the OnAction property of a dialog frame before the dialog box is displayed.

1.	With a dialog sheet active, select the dialog frame by clicking its border.

2.	On the Tools menu, click Assign Macro.

3.	In the Macro Name/Reference box, click the name of the procedure you want to run before the dialog box is displayed.

To assign the tab order of controls

When the user presses TAB repeatedly in a dialog box, the controls lose and gain the focus in a sequence, or tab order. You specify the tab order on the dialog sheet rather than in a Visual Basic procedure.

1.	With a dialog sheet active, click Tab Order on the Tools menu.

In the Tab Order dialog box, the controls on the dialog sheet are listed in the order in which they receive the focus.

2.	To change the tab order of the controls, select a control, and then click one of the Move arrows.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Returning data from a control

You can transfer the value of a control to a cell on a worksheet by linking the control to the cell. The link is a two-way connection: if the value of the cell is changed, the value of the control changes accordingly, and vice versa. For more information about linking controls to cells, see Linking controls to a cell or range.

The current value of a control can also be accessed directly by a Visual Basic procedure. The following example copies the text from an edit box on a dialog sheet into cell A1 on Sheet1.

Sub GetText()

newInfo = DialogSheets("Dialog1").EditBoxes("Edit Box 1").Text

Worksheets("Sheet1").Range("A1").Value = newInfo

End Sub

Tip   To return the text selection from a list box, use the Value property as an index into the array of list items returned by the List property.

You can run a macro in response to the value of a control. The following example checks the state of three option buttons and runs one of three macros, depending on which option button is selected.

Sub CheckButtons()

If DialogSheets("Dialog1").OptionButtons(1) = xlOn Then Macro1

If DialogSheets("Dialog1").OptionButtons(2) = xlOn Then Macro2

If DialogSheets("Dialog1").OptionButtons(3) = xlOn Then Macro3

End Sub

You could assign this procedure to the OK button on the dialog sheet so that the appropriate macro runs when the user clicks OK. For more information, see Assigning a macro to a control.

Note   A procedure can read and set the properties of a control before you display a dialog box, while it's visible, or after you close it. However, you can set the focus only while the dialog box is open.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Assigning a macro to a control

Just as you can assign a procedure to a button or graphic object, you can also assign a procedure to a control. This can be useful for validating or returning the data entered or for modifying the behavior of the controls or the dialog box while the dialog box is visible.

To assign an existing macro to a control

1.	Select the control.

2.	On the Tools menu, click Assign Macro.

3.	In the Macro Name/Reference box, enter the name of the procedure you want to run when the control is acted on.

To assign a new macro to a control

1.	Select the control.

2.	Click  [image].

Microsoft Excel opens a Visual Basic module displaying an empty procedure stub.

3.	Finish writing the procedure you want to run when the control is acted on.

Tip   To validate the data for all the controls in a dialog box, write a procedure that performs the following tasks, and then assign it to the OK button.

•	Evaluate the data in each control.

•	If a control contains invalid data, set the DismissButton property of the OK button to False, and display a message box indicating that one or more controls contain invalid data.

•	If all the controls contain valid data, set the DismissButton property of the OK button to True.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Displaying a custom dialog box

You use the Show method of the DialogSheet object to display a custom dialog box. The following procedure runs the dialog box contained in Dialog1.

Sub ShowDialog()

DialogSheets("Dialog1").Show

End Sub

While working on a dialog sheet, you can test your dialog box by clicking  [image]  on the Forms toolbar.

Note   Used with the Dialog object, the Show method displays a built-in Microsoft Excel dialog box. For more information, see Displaying built-in Microsoft Excel dialog boxes.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.


Summary of controls

Controls are special drawing objects you can use when you create dialog boxes. Some of them can also be used to enhance a worksheet or chart. For example, you can create a spinner that increments or decrements the value in an adjoining cell by 5 each time one of the arrows on the spinner is clicked.

To add a control to a sheet, use the corresponding button on the Forms toolbar.

For more information about inserting controls on a dialog sheet, see Creating a custom dialog box.

  Label

Static text. The font and background cannot be formatted.

  Edit Box

A box in which a user can enter text, numbers, or cell references. Dialog sheets only.

  Group Box

A border enclosing a group of controls.

  Create Button

A button the user can click to run the macro assigned to it. Buttons can also be used to cancel or dismiss a dialog box. You can type any text you want for the button label.

  Check Box

A small square box that appears checked, empty (cleared), or grayed, and which is not dependent on the state of other controls. If you establish a link between a cell and a check box, it is a two-way link. Typing TRUE or a nonzero value, FALSE or 0 (zero), or #N/A in the cell selects, clears, or grays the check box, respectively. Likewise, if the state of the check box changes, the linked cell reflects those changes.

  Option Button

A small round button that denotes a mutually exclusive option or setting, and which is grouped with one or more other option buttons. To group option buttons, place a group box around them. Otherwise, Microsoft Excel will consider all the option buttons on the sheet to be one mutually exclusive group.

Establishing a link between a cell and any of the option buttons in a group links the entire group of buttons to the cell. The value shown in the linked cell is the ordinal number of the selected button. (You can use the Tab Order command on the Tools menu to change this order.) Clearing the linked cell clears all the option buttons in the group.

  List Box

A list of text stings, one or more of which you can select. You can specify an input range of cells on a worksheet that contains the list of items you want to appear in the list box. You can also link the list box to a cell. The value shown in the linked cell is the ordinal number of the item currently selected in the list box. You can change or clear the number in the cell to change or clear the selection in the list box. (If the list box is formatted to allow multiple-item selections, the linked cell and the list box do not modify one another.)

  Drop-Down

An uneditable text box and an arrow paired with a drop-down list that appears when the user clicks the arrow. The properties of a drop-down list box are the same as those of a list box, except that only one item in a drop-down list box can be selected at a time.

  Combination List-Edit

An edit box combined with a list box. Dialog sheets only.

  Combination Drop-Down Edit

An edit box and an arrow paired with a drop-down list that appears when the user clicks the arrow. Dialog sheets only.

  Scroll Bar

A horizontal or vertical bar for changing numeric values. To create a horizontal scroll bar, drag horizontally. Scroll bars support a linked cell in which the position of the scroll box in the scroll bar is displayed as a number. Changing the number in the linked cell changes the position of the scroll box, and vice versa. Use the Object command on the Format menu to specify the minimum and maximum values and the amount of change associated with clicking a scroll arrow or the scroll bar.

  Spinner

Spinners are similar to scroll bars, except that they have only arrows; there is no "bar." Use the Object command on the Format menu to specify the starting and ending numbers and an increment for the value of the spinner.


Tips for using custom dialog boxes

The following tips may help you when you're working with custom dialog boxes. For general information about designing dialog boxes on dialog sheets, see Creating a custom dialog box.

•	Use DialogSheets(index).Show to display a custom dialog box. Use Application.Dialogs(xlDialogConstant).Show to display a built-in Microsoft Excel dialog box. For more information, see Displaying built-in Microsoft Excel dialog boxes.

•	Give the dialog sheet a name that's meaningful to you. To rename a sheet, double-click the sheet tab, and then type a new name in the Rename Sheet dialog box.

•	As you place controls on a dialog sheet, give each control a name that's meaningful to you. When you refer to the control in your Visual Basic code, a name you've created will be more useful than a default name such as "Check Box 1." To name a control, select it, type a name in the name box at the left end of the formula bar, and then press ENTER.

•	You cannot control where a custom dialog box is displayed. Microsoft Excel displays the dialog box in the same position as the dialog box that was last displayed.

•	To see which option button in a group is selected, check the Value property of each OptionButton object. For an example of this technique, see Returning data from a dialog box.

•	To create an edit box with password functionality, select the edit box, and then click Object on the Format menu. On the Control tab, select the Password Edit check box.

•	When calling a custom dialog box in an add-in, use the ThisWorkbook property to access the add-in workbook, as shown in the following example.

ThisWorkbook.DialogSheets("Dialog1").Show

When the workbook is saved as an add-in, the filename changes, so using the original workbook name with the Workbooks method fails.

•	To keep a dialog box visible until data is validated, you can change the DismissButton property for the OK button to False. After you validate the data, return the DismissButton property to True.

•	To display in an edit box an incremental change based on the value of a spinner, assign the following code to the spinner.

Sub ChangeEdit()

ActiveDialog.EditBoxes("Edit Box 1") _

.Text = ActiveDialog.Spinners("Spinner 1").Value

End Sub

•	If you want to avoid dismissing your dialog box when an option button or list box item is double-clicked, set the DefaultButton property to False for the default button, which is usually the OK button.

•	The following example shows an efficient way to display a series of dialog boxes.

Sub DisplayPanels()

If DialogSheets("Panel1").Show Then

If DialogSheets("Panel2").Show Then

If DialogSheets("Panel3").Show Then

'...

End If

End If

End If

End Sub

More Examples

For more examples of displaying and using custom dialogs, see Samples.xls in the Examples folder.


Working with charts

Microsoft Excel has two kinds of charts: embedded charts and chart sheets. Both kinds of charts are represented by Chart objects.

Embedded charts

Each Chart object that represents a chart embedded in a worksheet or dialog sheet is contained in a ChartObject object. You access a ChartObject object on a sheet by using the ChartObjects method; you then access the Chart contained in a ChartObject object by using the Chart property. For example, the following procedure changes the chart type of the embedded chart named "Chart 1" on Sheet1 to a 3-D pie chart.

Sub ThreeDee()

Sheets("Sheet1").ChartObjects("Chart 1").Chart.Type = xl3DPie

End Sub

Chart sheets

All Chart objects that represent charts on chart sheets in a workbook are contained in the Workbook object. You access the Chart objects in a Workbook object by using the Charts method or the Sheets method, as shown in the following examples.

Sub Bar()

Charts("Chart1").Type = xlBar

End Sub

Sub Pie()

Sheets("Chart1").Type = xlPie

End Sub

Modifying an existing chart

You may find it easiest to use an object variable when modifying a chart. For example, the following procedure declares an object variable named myChart and sets the variable equal to Chart1 on Sheet1 in the active workbook. The example then modifies the chart by using the object variable.

Sub EasyChart()

Dim myChart As Chart

Set myChart = Sheets("Sheet1").ChartObjects("Chart 1").Chart

myChart.Type = xl3DBar

myChart.HasTitle = True

myChart.ChartTitle.Text = "March Sales"

End Sub

Adding a new chart

You can add a new chart by using the Add method of either the Charts collection or the ChartObjects collection. In the following example, the object variable myChart is set to a new chart. The example then uses the ChartWizard method to define and format the new chart. The source data for the chart is defined as cells A1:B2 on Sheet1. The other arguments are the default selections made by the ChartWizard.

Sub NewChart()

Dim myChart As Chart

Set myChart = Charts.Add

myChart.ChartWizard Source:=Worksheets("Sheet1").Range("A1:B2"), _

Gallery:=xlColumn, Format:=6, PlotBy:=xlColumns, _

CategoryLabels:=1, SeriesLabels:=0, HasLegend:=1

End Sub

In the following example, the same chart is added as an embedded chart on Sheet1.

Sub NewEmChart()

Dim myChart As Chart

Set myChart = Sheets("Sheet1").ChartObjects.Add _

(50, 40, 200, 100).Chart

myChart.ChartWizard Source:=Worksheets("Sheet1").Range("A1:B2"), _

Gallery:=xlColumn, Format:=6, PlotBy:=xlColumns, _

CategoryLabels:=1, SeriesLabels:=0, HasLegend:=1

End Sub

Tips

•	If you're unsure as to how to create or change a particular element of a chart, record your actions and then examine the Visual Basic code.

•	While in a module, click in a word and then press F1 to display the Help topic for that keyword.


Working with graphic objects

In Microsoft Excel, graphic objects are shapes you draw on sheets by using the buttons on the Drawing toolbar. In Visual Basic, you create a graphic object by adding one to the appropriate collection. For example, you create a new oval by using the Add method of the Ovals collection.

You position graphic objects on a sheet by specifying the number of points (1/72 inch) the object is from the upper-left corner of the sheet; you also specify the width and height of the object in points. You can set the interior color of an object by using the RGB function.

The following procedures add a yellow oval, a red rectangle, and a text box to the first worksheet in the active workbook.

Sub AddYellowCircle()

With Worksheets(1).Ovals.Add(50, 70, 30, 30)

.Interior.Color = RGB(255, 255, 0)

End With

End Sub

Sub AddRedRect()

With Worksheets(1).Rectangles.Add(90, 70, 80, 30)

.Interior.Color = RGB(255, 0, 0)

End With

End Sub

Sub AddText()

With Worksheets(1).TextBoxes.Add(70, 90, 80, 30)

.Text = "My TextBox"

End With

End Sub

The following procedure uses the left edge, top edge, width, and height of the Range object myCell to determine the arguments for the Add method of the Ovals collection. The Add method creates a transparent oval with a red border just outside the cell border.

Sub CircleCell()

Dim myOval As Oval

Dim myCell As Range

Set myCell = Worksheets(1).Range("B5")

myLeft = myCell.Left - 2

myTop = myCell.Top - 2

myWidth = myCell.Width + 4

myHeight = myCell.Height + 4

Set myOval = Sheets("Sheet1").Ovals. _

Add(myLeft, myTop, myWidth, myHeight)

With myOval

.Border.ColorIndex = 3

.Interior.ColorIndex = xlNone

End With

End Sub

Tips

•	If you're unsure as to how to create or change a particular element of a graphic object, record your actions and then examine the Visual Basic code.

•	While in a module, click in a word and then press F1 to display the Help topic for that keyword.


How to loop through statements and make decisions

Using conditional statements and looping statements (also known as control structures), you can write Visual Basic code that makes decisions and repeats actions. Another useful control structure, the With statement, lets you to run a series of statements without having to requalify an object.

Using conditional statements to make decisions

Conditional statements evaluate whether a condition is True or False and then specify one or more statements to run, depending on the result. Usually, a condition is an expression that uses a comparison operator to compare one value or variable with another. For information about comparison operators in Visual Basic, see Operator Summary.

Which conditional statement do you want to use?

If...Then...Else: Branching when a condition is True or False

Select Case: Selecting a branch from a set of conditions

Using loops to repeat code

Looping allows you to run a group of statements repeatedly. Some loops repeat statements until a condition is False; others repeat statements until a condition is True. There are also loops that repeat statements a specific number of times or for each object in a collection.

Which loop do you want to use?

Do...Loop: Looping while or until a condition is True

For...Next: Using a counter to run statements a specified number of times

For Each...Next: Repeating a group of statements for each object in a collection

Running several statements on the same object

In Visual Basic, you usually need to specify an object before you can run one of its methods or change one of its properties. You can use the With statement to specify an object once for an entire series of statements.

With: Running a series of statements on the same object


Using With statements

The With statement is very useful in Visual Basic because it lets you specify an object once for an entire series of statements. With statements not only make your procedures run faster, but they help you avoid repetitive typing.

The following example fills a range of cells with the number 30, applies bold formatting, and sets the color of the interior of the cells to yellow.

Sub FormatRange()

With Worksheets("Sheet1").Range("A1:C10")

.Value = 30

.Font.Bold = True

.Interior.Color = RGB(255, 255, 0)

End With

End Sub

You can nest With statements for even greater efficiency. The following example inserts a formula into cell A1 and then formats the font.

Sub MyInput()

With Workbooks("Book1").Worksheets("Sheet1").Cells(1, 1)

.Formula = "=SQRT(50)"

With .Font

.Name = "Arial"

.Bold = True

.Size = 8

End With

End With

End Sub

Defining an object variable is another way to speed up your procedure and avoid repetitive typing. In the following example, the object variable myRange is set to a range on Sheet1. The object variable name is then used in the With statement and in other statements in the procedure.

Sub RandomRanges()

Dim myRange As Range

Set myRange = Worksheets("Sheet1").Range("A1:D12")

With myRange

.Formula = "=Rand()"

.Font.Bold = True

End With

myRange.Copy myRange.Offset(13, 5)

End Sub


Using If...Then...Else statements

You can use the If...Then...Else statement to run a specific statement or a group of statements, depending on the value of a condition. If...Then...Else statements can be nested to as many levels as you need. However, for better readability, you may want to use a Select Case statement rather than multiple levels of nested If...Then...Else statements.

Running statements if a condition is True

If you need to run only one statement when a condition is True, you can use the single-line syntax of the If...Then...Else statement. The following example shows the single-line syntax; note that this example omits the Else keyword.

Sub FixDate()

myDate = #2/13/95#

If myDate < Now Then myDate = Now

End Sub

If you want to run more than one line of code, you must use the multiple-line syntax. This syntax includes the End If statement, as shown in the following example.

Sub AddFormat()

Set c = Worksheets(1).Cells(1, 1)

If c.Font.Bold = True Then

c.Borders(xlBottom).LineStyle = xlDouble

c.Interior.ColorIndex = 6

End If

End Sub

Running certain statements if a condition is True, and running others if it is False

You can use an If...Then...Else statement to define two blocks of executable statements: one block runs if the condition is True, the other block runs if the condition is False.

Sub Rename()

Set wk = Worksheets(1)

If wk.Cells(1, 1).Font.Bold = True Then

heading = wk.Cells(1, 1).Value

wk.Name = heading

Else

MsgBox "Cannot rename worksheet."

End If

End Sub

Testing a second condition if the first condition is False

You can add ElseIf statements to an If...Then...Else statement to test a second condition if the first condition is False. For example, the following Function procedure computes a bonus based on the job classification. The statement following the Else statement runs if the conditions in all the If and ElseIf statements are False.

Function Bonus(performance, salary)

If performance = 1 Then

Bonus = salary * 0.1

ElseIf performance = 2 Then

Bonus = salary * 0.09

ElseIf performance = 3 Then

Bonus = salary * 0.07

Else

Bonus = 0

End If

End Function


Using Select Case statements

The Select Case statement is an alternative to using ElseIf in If...Then...Else statements to compare the same expression with several different values. Note that whereas If...Then...Else statements can evaluate a different expression for each ElseIf statement, the Select Case statement evaluates an expression only once, at the top of the control structure.

In the following example, the Select Case statement evaluates the performance argument that was passed to the function. Notice that each Case statement can contain more than one value, a range of values, or a combination of values and comparison operators. The Case Else statement (which is optional) runs if the Select Case statement does not match a value in any of the Case statements.

Function Bonus(performance, salary)

Select Case performance

Case 1

Bonus = salary * 0.1

Case 2, 3

Bonus = salary * 0.09

Case 4 To 6

Bonus = salary * 0.07

Case Is > 8

Bonus = 100

Case Else

Bonus = 0

End Select

End Function


Using Do...Loop statements

You can use Do...Loop statements to run a block of statements an indefinite number of times. The statements are repeated either while a condition is True or until a condition becomes True.

Repeating statements while a condition is True

There are two ways to use the While keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example). In the ChkFirstWhile procedure, if myNum were set to 9 instead of 20, the statements inside the loop would never run. In the ChkLastWhile procedure, the statements inside the loop run only once before the condition becomes False.

Sub ChkFirstWhile()

counter = 0

myNum = 20

Do While myNum > 10

myNum = myNum - 1

counter = counter + 1

Loop

MsgBox "The loop made " & counter & " repetitions."

End Sub

Sub ChkLastWhile()

counter = 0

myNum = 9

Do

myNum = myNum - 1

counter = counter + 1

Loop While myNum > 10

MsgBox "The loop made " & counter & " repetitions."

End Sub

Repeating statements until a condition becomes True

There are also two ways to use the Until keyword to check a condition in a Do...Loop statement. You can check the condition before you enter the loop (as shown in the first example following this paragraph), or you can check it after the loop has run at least once (as shown in the second example). As long as the condition is False, the looping occurs.

Sub ChkFirstUntil()

counter = 0

myNum = 20

Do Until myNum = 10

myNum = myNum - 1

counter = counter + 1

Loop

MsgBox "The loop made " & counter & " repetitions."

End Sub

Sub ChkLastUntil()

counter = 0

myNum = 1

Do

myNum = myNum + 1

counter = counter + 1

Loop Until myNum = 10

MsgBox "The loop made " & counter & " repetitions."

End Sub

Exiting a Do...Loop statement from inside the loop

You can exit a Do...Loop by using the Exit Do statement. Because you usually want to exit only in certain situations, such as to avoid an endless loop, you should use the Exit Do statement in the True statement block of either an If...Then...Else statement or a Select Case statement. If the condition is False, the loop should run as usual.

In the following example, myNum is assigned a value that would create an endless loop. The If...Then...Else statement checks for this condition, preventing the endless repetition.

Sub ExitExample()

counter = 0

myNum = 9

Do Until myNum = 10

myNum = myNum - 1

counter = counter + 1

If myNum < 10 Then Exit Do

Loop

MsgBox "The loop made " & counter & " repetitions."

End Sub

Note   To stop an endless loop, press ESC or CTRL+BREAK.


Using For...Next statements

You can use For...Next statements to run a block of statements a specific number of times. For loops use a counter variable whose value is increased or decreased with each repetition of the loop.

For example, the following procedure makes the computer beep 50 times. The For statement specifies the counter variable x and its start and end values. The Next statement increments the counter variable by 1.

Sub Beeps()

For x = 1 To 50

Beep

Next x

End Sub

Using the Step keyword, you can increase or decrease the counter variable by the value you specify. In the following example, the counter variable j is incremented by 2 each time the loop repeats. When the loop is finished, total is the sum of 2, 4, 6, 8, and 10.

Sub TwosTotal()

For j = 2 To 10 Step 2

total = total + j

Next j

MsgBox "The total is " & total

End Sub

To decrease the counter variable, you use a negative Step value. Note that to decrease the counter variable, you must specify an end value that is less than the start value. In the following example, the counter variable myNum is decreased by 2 each time the loop repeats. When the loop is finished, total is the sum of 16, 14, 12, 10, 8, 6, 4, and 2.

Sub NewTotal()

For myNum = 16 To 2 Step -2

total = total + myNum

Next myNum

MsgBox "The total is " & total

End Sub

Note   It is not necessary to include the counter variable name after the Next statement. In the preceding examples, the variable name was included for readability.

You can exit any For...Next statement before the counter reaches its end value by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit For statement in the True statement block of either an If...Then...Else statement or a Select Case statement. If the condition is False, the loop should run as usual.


Using For Each...Next statements

For Each...Next statements repeat a group of statements for each object in a collection. Visual Basic automatically sets an object variable each time the loop runs. For example, the following procedure closes every workbook except the workbook that contains the procedure that's running.

Sub CloseWorkbooks()

For Each wb In Application.Workbooks

If wb.Name <> ThisWorkbook.Name Then wb.Close

Next

End Sub

Looping through a range of cells

Using a For Each...Next loop is the easiest way to loop through the cells in a range. The following procedure loops through the range A1:D10 on Sheet1, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero()

For Each c In Worksheets("Sheet1").Range("A1:D10").Cells

If Abs(c.Value) < 0.01 Then c.Value = 0

Next

End Sub

The following example uses the CurrentRegion property to return the range, bounded by blank rows and columns, that contains the specified cell. It uses a For Each...Next loop to count the rows in the range that have a value greater than 50 in the second column.

Sub CountRows()

ctr = 0

Worksheets("Sheet1").Activate

For Each myRow In Cells(2, 1).CurrentRegion.Rows

If myRow.Columns(2).Value > 50 Then ctr = ctr + 1

Next

MsgBox ctr

End Sub

Exiting a For Each...Next loop before it is finished

You can exit a For Each...Next loop by using the Exit For statement. Because you usually want to exit only in certain situations, such as when an error occurs, you should use the Exit For statement in the True statement block of either an If...Then...Else statement or a Select Case statement. If the condition is False, the loop should run as usual.

The following example tests for the first cell in the range A1:B5 that does not contain a number. If such a cell is found, a message is displayed and Exit For exits the loop.

Sub TestForNumbers()

For Each c In Worksheets(1).Range("A1:B5").Cells

If IsNumeric(c.Value) = False Then

MsgBox "Range contains a non-numeric value."

Exit For

End If

Next c

End Sub


Looping through a range of cells

When using Visual Basic, you often need to run the same block of statements on each cell in a range of cells. To do this, you combine a looping statement and one or more methods to identify each cell, one at a time, and run the operation.

One way to loop through a range is to use the For...Next loop with the Cells method. Using the Cells method, you can substitute the loop counter (or other variables or expressions) for the cell index numbers. In the following example, the variable counter is substituted for the row index. The procedure loops through the range C1:C20, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero1()

For counter = 1 To 20

Set curCell = Worksheets("Sheet1").Cells(counter, 3)

If Abs(curCell.Value) < 0.01 Then curCell.Value = 0

Next counter

End Sub

Another easy way to loop through a range is to use a For Each...Next loop with the collection of cells returned by the Range method. Visual Basic automatically sets an object variable for the next cell each time the loop runs. The following procedure loops through the range A1:D10, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero2()

For Each c In Worksheets("Sheet1").Range("A1:D10").Cells

If Abs(c.Value) < 0.01 Then c.Value = 0

Next

End Sub

If you don't know the boundaries of the range you want to loop through, you can use the CurrentRegion property to return the range that surrounds the active cell. For example, the following procedure, when run from a worksheet, loops through the range that surrounds the active cell, setting to 0 (zero) any number whose absolute value is less than 0.01.

Sub RoundToZero3()

For Each c In ActiveCell.CurrentRegion.Cells

If Abs(c.Value) < 0.01 Then c.Value = 0

Next

End Sub

More examples

For more examples of looping through cells, see Samples.xls in the Examples folder.


Customizing menus

You can customize the Microsoft Excel menus or create your own menus by using the Menu Editor or Visual Basic code. Built-in menus and menu items belong to the Microsoft Excel application. Any changes you make to the menu system are stored in a menu-editing list for the active workbook. Each open workbook has it's own menu-editing list; when several workbooks are open, the menus show a combination of the menu-editing lists from all the open workbooks.

Adding new menu items to existing menus

Creating new menus and submenus

Creating new menu bars

Deleting and restoring menus and menu items


Adding new menu items to existing menus

If you want to add only one or two items to a menu, see Assign a macro to a Tools menu item. If you want to add a menu item to a menu other than the Tools menu, use the following procedure.

1.	With a Visual Basic module active, click Menu Editor on the Tools menu.

2.	In the Menu Bars box, click the name of a menu bar or the name of 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 click the name of 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. To add the new item to the bottom of the menu, click End Of Menu.

5.	Click Insert.

6.	In the Caption box, type the name you want for the new menu item.

Type an ampersand (&) before the character you want to use as the access key. To create a separator bar, type a hyphen (-).

7.	To specify the macro you want to run when the user clicks the menu item, enter the name of the procedure in the Macro box.

Note   You can click Restore All in the Menu Editor to restore built-in menu bars, menus, or menu items that you've deleted. You cannot restore custom menus components, however.

Adding menu items using Visual Basic

You can customize menus and menu items using Visual Basic code. You use the following methods to access custom menu components in Microsoft Excel: MenuBars, Menus, and MenuItems.

' Add a menu item

Sub AddItem()

MenuBars(xlWorksheet).Menus("File").MenuItems _

.Add Caption:="&My Command", _

OnAction:="MyMacro", Before:="Close"

End Sub


Creating new menus and submenus

You can add new menus and submenus to either a built-in or custom menu bar.

1.	With a Visual Basic module 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 the menu.

3.	In the Menus box, click the name of the menu to the left of which you want to insert the new menu. To add the menu to the right end of the menu bar, click End Of Menu Bar.

To add a submenu, click in the Menu Items box the name of the menu item from which you want the submenu to open.

4.	Click Insert.

5.	In the Caption box, type the name you want for the new menu or submenu.

Type an ampersand (&) before the character you want to use as the access key.

Note   You can click Restore All in the Menu Editor to restore built-in menu bars, menus, or menu items that you've deleted. You cannot restore custom menu components, however.

Creating menus and submenus using Visual Basic

You can customize menus and menu items using Visual Basic code. You use the following methods to access custom menu components in Microsoft Excel: MenuBars, Menus, and MenuItems.

' Add a menu to a menu bar

Sub AddMenu()

Set newMenu = MenuBars(xlChart).Menus. _

Add(Caption:="&MyWork", before:="Help")

End Sub

' Add a submenu to a menu

Sub AddSubMenu()

MenuBars(xlWorksheet).Menus("File").MenuItems _

.AddMenu Caption:="&More"

End Sub

' Add a submenu and items

Sub AddSubMenu()

Dim m As Menu

Set m = MenuBars(xlWorksheet).Menus("File")

m.MenuItems.AddMenu Caption:="&More"

m.MenuItems("More").MenuItems.Add Caption:="&My Command"

m.MenuItems("More").MenuItems.Add Caption:="&Your Command"

End Sub


Creating new menu bars

In Microsoft Excel, the menu bar changes automatically, depending on the type of sheet that is active. The Menu Editor treats groups of shortcut menus as menu bars.

You can create a new menu bar using the Menu Editor. However, you must use a Visual Basic procedure to display a custom menu bar.

To create a new menu bar

1.	With a Visual Basic module active, click Menu Editor on the Tools menu.

2.	In the Menu Bars box, click the name of any menu bar.

3.	Click Insert.

4.	In the Caption box, type the name you want for the new menu bar.

5.	Add whatever menu items and submenu items you want.

To display a custom menu bar

•	Write and run a Visual Basic procedure that applies the Activate method to a custom MenuBar object returned by MenuBars, as shown in the following example.

Sub ShowBar()

MenuBars("My New Bar").Activate

End Sub

To hide a custom menu bar

•	Write and run a Visual Basic procedure that activates a built-in menu bar, as shown in the following example.

Sub ShowModuleBar()

MenuBars(xlModule).Activate

End Sub

Note   Microsoft Excel limits the choice of built-in menu bars you can display, depending on the type of sheet that's active. For example, you cannot display the charting menu bar when a worksheet is active.

Creating a menu bar using Visual Basic

You can customize menus and menu items using Visual Basic code. You use the following methods to access custom menu components in Microsoft Excel: MenuBars, Menus, and MenuItems.

' Add a new menu bar

Sub AddMenuBar()

MenuBars.Add("My New Bar")

End Sub


Deleting and restoring menus and menu items

You can remove items from any of the built-in or custom menu bars or menus, and you can delete custom menu bars. You cannot delete a built-in menu bar, however.

To delete a menu bar, menu, or menu item

1.	With a Visual Basic module 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 you want to delete.

3.	Click Delete.

To restore a deleted built-in menu or menu item

1.	With a Visual Basic module 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, click the deleted item you want to restore.

4.	Click Undelete.

To restore all the built-in menus and menu items

This procedure restores only menus you've changed using the Menu Editor. You must use Visual Basic code to restore menus you've changed using Visual Basic code.

1.	With a Visual Basic module active, click Menu Editor on the Tools menu.

2.	Click Restore All.

Any custom menu bars, menus, or menu items are deleted, and the built-in Microsoft Excel menus are restored.

Deleting and restoring menus and menu items using Visual Basic

You can customize menus and menu items using Visual Basic code. You use the following methods to access custom menu components in Microsoft Excel: MenuBars, Menus, and MenuItems.

' Delete a menu

Sub DeleteMenu()

MenuBars(xlChart).Menus("MyWork").Delete

End Sub

' Restore a built-in menu

Sub RestoreMenu()

MenuBars(xlWorksheet).Menus.Add _

Caption:="&Edit", Before:=2, Restore:=True

End Sub

' Delete a menu item

Sub DeleteItem()

MenuBars(xlWorksheet).Menus("File") _

.MenuItems("My Command").Delete

End Sub

' Delete a submenu

Sub DeleteSubMenu()

MenuBars(xlWorksheet).Menus("File") _

.MenuItems("More").Delete

End Sub


Customizing toolbars

You can customize the Microsoft Excel toolbars and toolbar buttons without creating Visual Basic procedures. For more information, see the following topics.

Create a custom toolbar

Add or delete a toolbar button

Change the image on a toolbar button

When you quit Microsoft Excel, the toolbars in the workspace are saved in your Windows folder in a file with the extension .xlb. The .xlb filename is assigned by user name, so different users can have different toolbar configurations on the same computer.

You can move a custom toolbar from the workspace to a workbook. Workbook-level toolbars make it easy to create a polished user interface for a custom application, and workbooks are a convenient way to distribute toolbars.

To move a toolbar to a workbook

1.	With a Visual Basic module 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.

Customizing toolbars and toolbar buttons using Visual Basic

You can customize toolbars and toolbar buttons using Visual Basic code. You use the following methods to access built-in and custom toolbar components: Toolbars and ToolbarButtons.

Note   For a list of toolbar button ID values, see Toolbar Button ID Values.

' Add a new toolbar

Sub AddToolbar()

Toolbars.Add "MyToolbar"

End Sub

' Add toolbar buttons

Sub AddButtons()

With Toolbars("MyToolbar").ToolbarButtons

.Add Button:=1, Before:=1

.Add Button:=2, Before:=2

.Add Button:=240, Before:=3

End With

End Sub

' Position a toolbar

Sub Position()

With Toolbars("MyToolbar")

.Position = xlFloating

.Left = 60

.Top = 28

.Width = 90

End With

End Sub

' Display a toolbar

Sub ShowBar()

Toolbars("MyToolbar").Visible = True

End Sub

' Copy buttons

Sub CopyButton()

Toolbars(1).ToolbarButtons(10).Copy _

Toolbar:=Toolbars("MyToolbar"), Before:=4

End Sub

' Move buttons

Sub MoveButton()

Toolbars(1).ToolbarButtons(11).Move _

Toolbar:=Toolbars("MyToolbar"), Before:=5

End Sub

Tip   If you're unsure as to which method or property to use when working with a toolbar or toolbar button, you can always record your actions and then examine the Visual Basic code.


Rules for using parentheses

Sub procedures, built-in statements, and some methods do not return a value. When you call one of these, you don't enclose its arguments in parentheses, as shown in the following example.

MySub "stringArgument", integerArgument

Function procedures, built-in functions, and some methods do return a value. If you're ignoring the return value, you don't include parentheses. In this respect, you call the function just as you would call a Sub procedure. You omit the parentheses and list the arguments (if any), and you don't assign the function to a variable, as shown in the following example.

MsgBox "Task Completed!", 0, "Task Box"

If you want to use the return value of a function, you need to enclose the arguments in parentheses, as shown in the following example.

Answer3 = MsgBox("Are you happy with your salary?", 4, "Question 3")

A statement in a Sub or Function procedure can pass values to a called procedure using named arguments. The guidelines for using parentheses apply, whether or not you're using named arguments. When you use named arguments, you can list them in any order, and you can omit optional arguments. Named arguments are always followed by a colon and an equal sign (:=) and then the argument value.

The following example calls the MsgBox function using named arguments, and it ignores the return value.

MsgBox Title:="Task Box", Prompt:="Task Completed!"

The following example calls the MsgBox function using named arguments, and it assigns the return value to the variable answer3.

answer3 = MsgBox(Title:="Question 3", _

Prompt:="Are you happy with your salary?", Buttons:=4)


Using built-in dialog boxes

Before you start designing custom dialog boxes, consider using the dialog boxes that are built into Visual Basic.

Using built-in dialog boxes for input and output

Using built-in dialog boxes to return file information

Displaying built-in Microsoft Excel dialog boxes


Using built-in dialog boxes for input and output

The InputBox function displays a dialog box with a message and an edit box. When the user clicks OK, the function returns the text that the user entered.

The MsgBox function displays a simple message. You can display several different command buttons and icons. This function returns a number that indicates which button was clicked.

In the following example, the first statement creates the variable myVar, which stores the string entered by the user. The second statement displays the string in a message box.

Sub GetName()

myVar = InputBox(Prompt:="Please type your name:")

MsgBox Prompt:=myVar, Buttons:=vbExclamation, Title:="Your name is"

End Sub

The InputBox method of the Application object is similar to the InputBox function, but it includes an optional argument, type, for checking the type of data returned.


Using built-in dialog boxes to return file information

You can display built-in dialog boxes that return file information to your procedures; these are similar to the standard Open and Save As dialog boxes.

The GetOpenFilename method displays a dialog box that resembles the standard Open dialog box. This method does not open a file, but it returns the name of the file chosen by the user. In the following example, the Do...Loop statement displays the dialog box until the variable myFilename contains data.

Sub GetFile()

Do

myFilename = Application.GetOpenFilename

Loop Until myFilename <> False

MsgBox myFilename

End Sub

The GetSaveAsFilename method is similar to GetOpenFilename. There is an additional optional argument, initialFilename, which sets the default name displayed in the File Name box. Again, the file is not saved, but the filename specified by the user is returned.

Sub MySaveAs()

Do

myFilename = Application.GetSaveAsFilename("Mybook.xls")

Loop Until myFilename <> False

MsgBox myFilename

End Sub


Displaying built-in Microsoft Excel dialog boxes

You can display a built-in dialog box to get user input or to control Microsoft Excel by using Visual Basic. You can display many of the built-in Microsoft Excel dialog boxes by using the Show method of the Dialog object. To access a built-in Microsoft Excel dialog box, you must specify the correct constant for the index argument of the Dialogs method. The following example displays the Open dialog box (xlDialogOpen).

Sub Main()

Application.Dialogs(xlDialogOpen).Show

End Sub

You can find the list of available dialog box constants (all beginning with "xlDialog") by using the Object Browser.

To find the list of Microsoft Excel dialog box constants

1.	Activate a module in a Microsoft Excel workbook.

2.	On the View menu, click Object Browser.

3.	In the Libraries/Workbooks box, click the Microsoft Excel library.

4.	In the Objects/Modules box, click Constants.

5.	In the Methods/Properties box, scroll until you see the constants that start with "xlDialog".

The return value of the Show method indicates which command button the user clicked to close the dialog box. False indicates that the Cancel button was clicked; True indicates that the OK button was clicked.

Tips

•	You cannot display a Microsoft Excel dialog box outside its normal context. For example, if the dialog box is normally displayed only when a worksheet is active, the Show method will fail if you run the procedure when the active sheet is not a worksheet.

•	To set default values for a built-in dialog box, include the corresponding macro function arguments after the Show method. For more information, see Built-In Dialog Box Argument Lists.


Using Microsoft Excel worksheet functions in Visual Basic

You can use most Microsoft Excel worksheet functions in your Visual Basic statements. To see a list of the Microsoft Excel worksheet functions you can use, see List of Worksheet Functions Available to Visual Basic.

Note   Some worksheet functions are not useful in Visual Basic. For example, the Concatenate function is not needed because in Visual Basic you can use the & operator to join multiple text values.

Calling a worksheet function from Visual Basic

In Visual Basic, the Microsoft Excel worksheet functions are available through the Application object; any statement that uses a worksheet function must use the Application qualifier.

The following Sub procedure uses the Min worksheet function to determine the lowest value in a range of cells. First, the variable myRange is declared as a Range object, and then it is set to range A1:C10 on Sheet1. Another variable, answer, is assigned the result of applying the Min function to myRange. Finally, the value of answer is displayed in a message box.

Sub UseFunction()

Dim myRange As Range

Set myRange = Worksheets("Sheet1").Range("A1:C10")

answer = Application.Min(myRange)

MsgBox answer

End Sub

If you use a worksheet function that requires a range reference as an argument, you must specify a Range object. For example, you can use the Match worksheet function to search a range of cells. In a worksheet cell, you would enter a formula such as =MATCH(9,A1:A10,0). However, in a Visual Basic procedure, you would specify a Range object to get the same result.

Sub FindFirst()

myVar = Application.Match(9, Worksheets(1).Range("A1:A10"), 0)

MsgBox myVar

End Sub

Note   Visual Basic functions do not use the Application qualifier. A function may have the same name as a Microsoft Excel function and yet work differently. For example, Application.Log and Log will return different values.

Inserting a worksheet function into a cell

To insert a worksheet function in a cell, you specify the function as the value of the Formula property of the corresponding Range object. In the following example, the RAND worksheet function (which generates a random number) is assigned to the Formula property of range A1:B3 on Sheet1 in the active workbook.

Sub InsertFormula()

Worksheets("Sheet1").Range("A1:B3").Formula = "=RAND()"

End Sub


Making procedures run automatically

An event is an action such as opening a workbook, switching to a sheet, or recalculating a worksheet. You can run procedures automatically when certain events happen. There are several different ways you can approach this.

•	You can assign a macro to a menu item, toolbar button, key combination, or graphic object.

Assign a macro

•	You can give a procedure a name that tells Visual Basic that it must run the procedure automatically.

Running procedures when you open or close a workbook

•	You can assign procedures to properties that correspond to specific events.

Running procedures when you activate or deactivate a sheet

Running procedures when an event occurs


Running procedures when you open or close a workbook

When you open a workbook, Microsoft Excel automatically runs the Sub procedure called Auto_Open, if it exists; when you close the workbook, Microsoft Excel runs the Sub procedure Auto_Close. You create and test an Auto_Open or Auto_Close procedure just as you would create and test any other Sub procedure. Each workbook can contain only one Auto_Open procedure and one Auto_Close procedure. However, the Auto_Open and Auto_Close procedures can call other Sub or Function procedures.

The following example adds a new worksheet with the name the user enters each time he or she opens the workbook.

Sub Auto_Open()

Worksheets.Add.Name = InputBox(Prompt:="Please enter a name for your worksheet")

End Sub

Tip   You can have Microsoft Excel open a particular workbook each time it starts. You do this by saving the workbook in the startup folder (XLSTART).


Running procedures when you activate or deactivate a sheet

You can assign an existing procedure to run automatically when you activate or deactivate a sheet. To do this, you set either the OnSheetActivate or OnSheetDeactivate property. These property values are saved with the workbook, so you only need to set the values once and then save the workbook.

The procedure you specify to run does not have to be open. You can set the procedure to run when you activate or deactivate a specified sheet, any sheet in a specified workbook, or any sheet in any open workbook.

In the following example, the PrepBook procedure sets the OnSheetActivate property of Sheet1 to the AutoSheet procedure in Module1.

Sub PrepBook()

Worksheets("Sheet1").OnSheetActivate = "Module1.AutoSheet"

End Sub

Sub AutoSheet()

answer = MsgBox(Prompt:="Are you an exempt employee?", Buttons:= 4)

If answer = 6 Then Worksheets("Sheet2").Activate _

Else Worksheets("Sheet3").Activate

End Sub


Running procedures when an event occurs

There are many events that occur in Microsoft Excel that you may want to respond to by running a procedure automatically. You can assign an existing procedure to a property (such as OnSheetActivate, OnAction, or OnCalculate) or specify an existing procedure in a method (such as OnTime or OnKey). You only need to set the property or execute the method once and then save the changes. These setting are saved with the workbook.

You can assign a procedure to any of the following properties: OnAction, OnCalculate, OnData, OnDoubleClick, OnEntry,, OnSheetActivate, OnSheetDeactivate, OnWindow.

You can specify a procedure in any of the following methods: OnKey, OnRepeat, OnTime, OnUndo, SetLinkOnData.

The following example uses the OnTime method to print a report one minute after the RunReport procedure is called.

Sub RunReport()

Application.OnTime _

EarliestTime:=Now + TimeValue("00:01:00"), _

Procedure:="ReportSub"

End Sub

Sub ReportSub()

' Statements to print report

MsgBox "Report is Printing!"

End Sub


Rules for naming procedures, arguments, variables, and constants

Use the following rules when naming your procedures, constants, variables, and arguments in a Visual Basic module:

•	The first character must be a letter.

•	You cannot use a space, period (.), exclamation point (!), @, &, $, or # in the name.

•	You cannot use any restricted keywords. For a list of these, see Restricted Keywords.

•	You cannot repeat names within the same scoping level. For example, you could not declare two variables named age within the same procedure. You could, however, declare a private variable named age and a procedure-level variable named age within the same module. For more information, see Understanding scope.

Note   Visual Basic ignores uppercase and lowercase, but it preserves the capitalization in the statement where the name is declared.


Visual Basic data types

When you declare a constant, variable, or argument, you are telling the macro what to name it. At the same time, you can specify what kind of data it can contain. For example, the following statement creates a variable named answer and specifies that its data type is Boolean (True or False).

Dim answer As Boolean

Constants, variables, and arguments (variables that you define in Sub and Function procedure declarations) can be assigned a data type. The available data types include the following: Boolean, Currency, Date, Double, Integer, Long, Single, String, Variant. Any variable or argument can also be declared as Object or a user-defined type.

For an overview of all the data types, see Data Type Summary. For simplified information about the following data types, see these topics:

Quick overview of the Variant data type

Using object variables in Microsoft Excel


Quick overview of the Variant data type

If you do not specify a data type when you declare a constant, variable, or argument, Visual Basic automatically specifies the Variant data type. The advantages of variables declared as this data type are that they can contain string, date, time, Boolean, or numeric values, and they can convert the values they contain automatically. The disadvantage is that variant values require 16 bytes of memory, which is only significant in large procedures or complex modules. You would rarely use the Variant data type for a constant.

The following statements create variant variables.

Dim myVar

Dim yourVar As Variant

theVar = "This is some text."

The last statement does not explicitly declare the variable theVar, but rather declares the variable implicitly, or automatically. Variables that are declared implicitly are specified as the Variant data type.

Tip   If you use the wrong data type for a variable or argument after a data type has been specified for it, a data type error will occur. To avoid data type errors, you should either use only implicit variables (the Variant data type) or explicitly declare all your variables and specify a data type.


Using object variables in Microsoft Excel

You can declare a variable that will contain an object as one of three data types: Variant, Object, or a specific Microsoft Excel object. Each of the following three statements declares a variable that can be assigned a Microsoft Excel object.

Dim myCell

Dim yourCell As Object

Dim theCell As Range

The first statement declares myCell, and Visual Basic automatically specifies the Variant data type. You can also declare a variant variable implicitly in a Set statement that assigns an object to the variable, as shown in the following statement.

Set myCell = Worksheets(1).Range("A1")

The second declaration declares yourCell and specifies the Object data type. This is a generic data type that can hold any type of object. You specify the exact object with a Set statement. For more information, see Creating an Object Variable.

The third declaration defines theCell as a Microsoft Excel Range object. You can declare an object variable to be any object in the Microsoft Excel object hierarchy. For information about the Microsoft Excel object hierarchy, see Microsoft Excel Objects.

The following example declares myCell as an object variable and sets the value to cell A1. The range is then modified using the variable name.

Sub SetCellValue()

Dim myCell As Range

Set myCell = Worksheets("Sheet1").Range("A1")

With myCell

.Value = 800

.Font.Bold = True

End With

End Sub


Changing Visual Basic options

On the Tools menu, click Options. On the Module General tab, you can specify settings for the following options.

To specify	Set
The width of the indent for nested statements	Tab Width
Whether nested statements are indented automatically when you press ENTER	Auto Indent
Whether error messages are displayed when syntax errors are detected while you are editing a procedure	Display Syntax Errors
Whether a procedure stops when any error occurs	Break On All Errors
Whether the Option Explicit statement is inserted automatically in each new module	Require Variable Declaration
The current language or country and its corresponding settings	Language/Country
On the Module Format tab, you can specify settings for the following options.

To specify	Set
The default font used in modules	Font
The size of the default font	Size
Under Code Colors on the Module Format tab, you can use Foreground and Background to specify the colors for the selected item in the list of code elements.

To specify	Select in the list of code elements
The color of the selection	Selection Text
The color of statements that contain syntax errors	Syntax Error Text
The color of the next statement to execute when stepping through a procedure	Execution Point Text
The color of breakpoints created for debugging	Breakpoint Text
The color of comments	Comment Text
The color of Visual Basic keywords	Keyword Text
The color of procedure, constant, variable, argument names	Identifier Text
The color of all other text	Normal Text


Writing a Sub procedure

A Sub procedure is a series of Visual Basic statements, enclosed by the Sub and End Sub statements, that performs actions but does not return a value. A Sub procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Sub procedure has no arguments, its Sub statement must include an empty set of parentheses.

The following Sub procedure has comments explaining each line.

Sub GetInfo()

' Declares a procedure named GetInfo - this Sub procedure takes no arguments

Dim answer As String

' Declares a string variable named answer

answer = InputBox(Prompt:="What is your name?")

' Assigns the return value of the InputBox function to answer

If answer = Empty Then

' Conditional If...Then...Else statement

MsgBox Prompt:="You did not enter a name."

' Calls the MsgBox function (executable statement)

Else

MsgBox Prompt:="Your name is " & answer

' MsgBox function concatenated with the variable answer (executable statement)

End If

' Ends the If...Then...Else statement

End Sub

' Ends the Sub procedure

Statements

The body of a Sub procedure contains statements. A statement is a combination of Visual Basic keywords, variables, constants, or expressions.

 	Writing Visual Basic statements

Variables and constants

You can declare variables or constants inside or outside of a Sub procedure. Declarations inside a Sub procedure are at the procedure level.

 	Declaring variables

 	Declaring constants

Arguments in Sub procedures

An argument is a place holder for a value that is needed by the Sub procedure to complete its task. You define an argument in the Sub statement itself. You must provide a name for each argument, and you can specify a data type if you want.

In the following example, the Sub procedure Main passes two arguments to the Sub procedure MyName. The arguments passed must match the type specified in the called Sub procedure. In this case, the arguments are strings.

Sub Main()

MyName "Claudia", "Tanner"

End Sub

Sub MyName(first As String, last As String)

MsgBox "My name is " & first & " " & last

End Sub

By default, all Visual Basic procedures pass arguments by reference, which means that the value of any given argument can be changed by the called procedure. If you want the called procedure to use the argument without changing its value, you pass the argument by value.

In the following example, the value of the argument first in the called Sub procedure MyName is changed. However, because the argument is passed by value, the variable startString retains its original value in the Sub procedure Main. If you remove the ByVal keyword from the Sub statement of the procedure MyName, the startString variable is changed after being passed.

Sub Main()

Dim startString As String

startString = "Pat"

MyName startString

MsgBox startString

End Sub

Sub MyName(ByVal first As String)

first = first & " Crenshaw"

MsgBox "My name is " & first

End Sub

Tip   If you want to learn more about how to write a Sub procedure, see Working in a module.


Writing a Function procedure

A Function procedure is a series of Visual Basic statements enclosed by the Function and End Function statements. A Function procedure is similar to a Sub procedure, but a function can also return a value. A Function procedure can take arguments (constants, variables, or expressions that are passed by a calling procedure). If a Function procedure has no arguments, its Function statement must include an empty set of parentheses. A function returns a value by assigning a value to its name in one or more statements of the procedure.

Note   If you intend to call your function from a worksheet, you must be aware of certain limitations, which are described in Writing a user-defined worksheet function. If your function is only being called from another Visual Basic procedure, the limitations do not apply.

In the following example, the Celsius function calculates degrees Celsius from degrees Fahrenheit and then uses the Round worksheet function to round the result up or down to two decimal places. When the function is called from the Main procedure, a variable containing the argument value is passed to the function. The rounded answer is returned and displayed in a message box.

Sub Main()

temp = Application.InputBox(Prompt:= _

"Please enter the temperature in degrees F.", Type:=1)

MsgBox "The temperature is " & Celsius(temp) & " degrees C."

End Sub

Function Celsius(fDegrees)

Celsius = (fDegrees - 32) * 5 / 9

Celsius = Application.Round(Celsius, 2)

End Function


Writing a user-defined worksheet function

A user-defined worksheet function is a Function procedure designed to be called from a formula in a worksheet.

Generally, a user-defined worksheet function makes a calculation and returns a value. You can enter the Function procedure name in a worksheet cell and return a value to the cell the same way you use a built-in Microsoft Excel worksheet function.

User-defined worksheet functions can replace one long formula or several formulas. You can combine mathematical expressions, built-in Microsoft Excel worksheet functions, and Visual Basic code. User-defined worksheet functions can also work with text, dates, and values.

A user-defined worksheet function cannot set properties or execute methods that 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 views

You can avoid most errors by creating user-defined worksheet functions that make calculations based only on information that you provide or that can be retrieved from Microsoft Excel.

In the following example, the Celsius function converts degrees Fahrenheit to degrees Celsius and then uses the Round worksheet function to round the result up or down to two decimal places.

Function Celsius(fDegrees As Integer)

Celsius = (fDegrees - 32) * 5 / 9

Celsius = Application.Round(Celsius, 2)

End Function

After copying this example into a module, you can use the Celsius function in a worksheet by clicking the Function Wizard button and typing a value for fDegrees.

Function Wizard button

 Tips for writing user-defined worksheet functions

•	Use unique names for functions and arguments.

•	Include one or more statements in your function that assign a return value to the function name.

•	If you are concerned about saving memory, specify a data type for your function and its arguments. Values passed to the function must match the argument data type.

•	If you want the argument of a function to be a cell or range, use the Object data type.

•	When using built-in worksheet functions in Visual Basic statements, precede the function name with the Application object qualifier.

•	You can use the Object Browser to assign your function to a function category or add a description. In the Function Wizard, your function name will be listed when the specified category is selected, and the description will appear when your function name is selected.


Writing Visual Basic statements

A statement in Visual Basic is a complete instruction; it can contain keywords, operators, variables, constants, and expressions. Each statement belongs to one of the following three categories:

•	Declaration statements, which name a variable, constant, or procedure and can also specify a data type.

 	Writing declaration statements

•	Assignment statements, which assign a value or expression to a variable or constant.

Writing assignment statements

•	Executable statements, which initiate actions. These statements can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.

Writing executable statements

Continuing a statement over multiple lines

A statement usually fits on one line, but you can continue a longer statement into the next line by typing a space and then an underscore. In the following example, the MsgBox executable statement is continued over three lines.

Sub DemoBox()  'This procedure declares a string variable,

' assigns it the value Claudia, and then displays

' a concatenated message.

Dim myVar As String

myVar = "Claudia"

MsgBox Prompt:="Hello " & myVar, _

Title:="Greeting Box", _

Buttons:=vbExclamation

End Sub

Adding comments

Comments can explain a procedure or a particular instruction to you or others reading your code. Visual Basic ignores comments when it runs your procedures. Comment lines (beginning with an apostrophe, or with Rem and a space) can be added anywhere in a procedure. To add a comment to the same line as a statement, insert an apostrophe after the statement, followed by the comment. By default, comments are green.

Checking syntax errors

If you press ENTER after typing a line of code and the line turns red (an error message may display as well), you'll need to find out what's wrong with your statement and then correct it. For information about troubleshooting your statement, see Checking your code for language errors.


Writing declaration statements

You use declaration statements to name and define procedures, variables, arrays, and constants. When you declare a procedure, variable, or constant, you also define its scope, depending on where you place the declaration and what keywords you use to declare it.

The following example contains three declarations.

Sub ApplyFormat()

Const limit As Integer = 33

Dim myCell As Range

' More statements

End Sub

The Sub statement (with its matching End Sub statement) declares a procedure named ApplyFormat. All the statements enclosed by the Sub and End Sub statements are executed whenever the ApplyFormat Sub procedure is called or run.

Writing a Sub procedure

The Const statement declares the constant limit, specifying the Integer data type and a value of 33.

Declaring constants

The Dim statement declares the variable myCell. The data type is an object --- in this case, a Range object. You can declare a variable to be any Microsoft Excel object. Dim statements are one type of statement used to declare variables. Other keywords used in declarations are Redim, Static, Public, Private, and Const.

Declaring variables


Writing assignment statements

Assignment statements assign a value or expression to a variable or constant. Assignment statements always include an equal sign (=). The following example assigns the return value of the InputBox function to the variable yourName.

Sub Question()

Dim yourName As String

yourName = InputBox("What is your name?")

MsgBox "Your name is " & yourName

End Sub

The Let statement is optional and is usually omitted. In the preceding example, the assignment statement could be written Let yourName = InputBox("What is your name?").

The Set statement is used to assign an object to a variable that has been declared as an object. The Set keyword is required. In the following example, the Set statement assigns a range on Sheet1 to the object variable myCell.

Sub ApplyFormat()

Dim myCell As Range

Set myCell = Worksheets("Sheet1").Range("A1")

With myCell.Font

.Bold = True

.Italic = True

End With

End Sub

Statements that set property values are also assignment statements. The following example sets the Bold property of the Font object for the active cell.

ActiveCell.Font.Bold = True


Writing executable statements

Executable statements initiate actions. They can execute a method or function, and they can loop or branch through blocks of code. Executable statements often contain mathematical or conditional operators.

Sub ApplyFormat()

Const limit As Integer = 33

For Each c In Worksheets("Sheet1").Range("MyRange").Cells

If c.Value > limit Then

With c.Font

.Bold = True

.Italic = True

End With

End If

Next c

MsgBox "All done!"

End Sub

The preceding example uses a For Each...Next statement to iterate through each cell in a range named MyRange on Sheet1 of the active workbook. The variable c is a cell in the collection of cells contained in MyRange.

The If...Then...Else statement checks the value of the cell. If the value is greater than 33, the With statement sets the Bold and Italic properties of the Font object for that cell. If...Then...Else statements end with End If.

The With statement can save typing because the statements it contains are automatically executed on the object following the keyword With.

The Next statement calls the next cell in the collection of cells contained in MyRange.

The MsgBox function (which displays a built-in Visual Basic dialog box) displays a message indicating that the Sub procedure is finished running.


Declaring variables

The simplest way to declare a variable in Visual Basic is to use it in an assignment statement. When a new variable appears in an assignment statement, Visual Basic implicitly (automatically) creates the variable for you and specifies the Variant data type. For example, the following Sub procedure creates the variable message and assigns it the value "Hello!" in one statement.

Sub MyDialog()

msg = "Hello!"

MsgBox msg

End Sub

If you don't want Visual Basic to make implicit declarations, you can place the Option Explicit statement in a module before any procedures. This statement requires you to explicitly declare all variables within the module. This means that you must specify the variable name for each variable in the module by writing one or more declaration statements. You can specify the data type of a variable in a declaration statement, as well.

If you are required to declare all variables, you are less likely to make typing errors. That is, if you misspell a variable name while Option Explicit is in effect, the statement that contains the misspelling will cause a syntax error. If Option Explicit is not in effect, Visual Basic will assume that you are creating a new variable; your procedure may run without error, but it may produce unexpected results.

To have Visual Basic automatically place the Option Explicit statement in all of your modules, click Options on the Tools menu, and then click the Module General tab. Select the Require Variable Declaration check box.

Note   You must explicitly declare fixed arrays and dynamic arrays. For more information, see Using arrays in Visual Basic.

Dim statement

When declaring variables, most often you will use a Dim statement. These declaration statements can be placed either within a procedure or at the top of a module. For example, the following statement creates the variable myName and specifies the String data type.

Dim myName As String

If this statement appears inside a procedure, myName can be used in that procedure only. If the statement appears at the top of the module, myName is available to all procedures within the module, but not to other modules in the same workbook.

For information about naming your variables, see Rules for naming procedures, arguments, variables, and constants.

Variables can be declared as one of the following data types: Boolean, Integer, Long, Currency, Single, Double, Date, String (for variable-length strings), String * length (for fixed-length strings), Object, or Variant. If you do not specify a data type, the Variant data type is assigned by default.

You can declare several variables in one statement. If you want to specify a data type, you need to include the data type for each variable. In the following statement, the variables b, c, and d are declared as Integer.

Dim b As Integer, c As Integer, d As Integer

In the following statement, x and y are declared as Variant; only z is declared as Integer.

Dim x, y, z As Integer

Public statement

The Public statement is used like the Dim statement, except that it only appears outside procedures, placed at the top of the module.

Public MyName As String

When you declare a public variable, that variable can be used in all procedures in all modules in the workbook. It can also be used in any workbooks that reference the workbook where the public variable is declared. For more information, see Calling procedures in other workbooks.

Private statement

The Private statement, like the Public statement, only appears outside procedures, placed at the top of the module. When you use the Private statement, the variable it declares can be used only in procedures in the same module.

Private MyName As String

Note   The Dim statement, when used at the module level, is equivalent to the Private statement.

Static statement

Before you assign a value to a declared variable, it has a default value according to its data type. Whenever a procedure is called, each variable declared in that procedure is reset to its default value automatically, unless you declared the variable with the Static statement.

Static MyNum As Integer

When you use the Static statement instead of a Dim statement, the declared variable will retain its value between calls. You can also use the Static keyword in a Sub or Function statement to specify that all the variables declared implicitly or explicitly within the procedure are static. For more information, see Lifetime of variables.


Declaring constants

A constant allows you to assign a meaningful name to a value. After a constant is declared, it cannot be modified or assigned a new value. You use the Const statement to declare a constant and set the value.

The following example declares the public constant age, an integer assigned the value 34.

Public Const age As Integer = 34

For information about naming your constants, see Rules for naming procedures, arguments, variables, and constants.

Constants can be declared as one of the following data types: Boolean, Integer, Long, Currency, Single, Double, Date, String, or Variant. Because you know the value of a constant, you would usually specify the data type in a Const statement.

You can declare several constants in one statement. If you want to specify a data type, you need to include the data type for each constant. In the following statement, the constants age and wage are declared as Integer.

Const age As Integer = 34, wage As Integer = 35000

A constant can be declared at either the procedure level or the module level. The same scoping levels that apply to variables apply to constants. For more information, see Understanding scope.


Using built-in constants

Visual Basic includes many built-in constants. The specific built-in constants used with a particular function, method, or property are described in the reference topic for that function, method, or property. For example, the topic for the MsgBox function includes a table of constants that represent the numeric values of different buttons you can display in a message box. The constants vbOKOnly and vbYesNoCancel are meaningful, while their corresponding numbers are not.

To see a list of the Visual Basic built-in constants

1.	Activate a module in a Microsoft Excel workbook.

2.	On the View menu, click Object Browser.

3.	In the Libraries/Workbooks box, select VBA.

4.	In the Objects/Modules box, select Constants.

All the Visual Basic constants are listed in the Methods/Properties box. Each constant name begins with the letters "vb".

To see a list of the Microsoft Excel built-in constants

1.	Activate to a module in a Microsoft Excel workbook.

2.	On the View menu, click Object Browser.

3.	In the Libraries/Workbooks box, select Excel.

4.	In the Objects/Modules box, select Constants.

All the Microsoft Excel constants are listed in the Methods/Properties box. Each constant name begins with the letters "xl".


Calling Sub and Function procedures

To call a Sub procedure from another procedure, you just type the name of the procedure along with values for any required arguments. The Call statement is not required, but if you do use it, you must enclose any arguments in parentheses.

You can use a Sub procedure to organize your other procedures. This technique makes your procedures easier to understand and debug. In the following example, the Sub procedure Main calls the Sub procedure MultiBeep, passing the value 56 for its argument. After MultiBeep runs, control returns to Main, and Main then calls the Sub procedure Message. Message displays a message box; when the user clicks OK, control returns to Main, and Main finishes.

Sub Main()

MultiBeep 56

Message

End Sub

Sub MultiBeep(numbeeps)

For counter = 1 To numbeeps

Beep

Next counter

End Sub

Sub Message()

MsgBox "Time to take a break!"

End Sub

Calling Sub procedures with more than one argument

The following example shows two ways to call a Sub procedure with more than one argument. The second time HouseCalc is called, parentheses are required around the arguments because the Call statement is used.

Sub Main()

HouseCalc 99800, 43100

Call HouseCalc(380950, 49500)

End Sub

Sub HouseCalc(price As Single, wage As Single)

If 2.5 * wage <= 0.8 * price Then

MsgBox "You cannot afford this house."

Else

MsgBox "This house is affordable."

End If

End Sub

Using parentheses when calling Function procedures

If you want to use the return value of a function, you need to assign the function to a variable and enclose the arguments in parentheses, as shown in the following example.

Answer3 = MsgBox("Are you happy with your salary?", 4, "Question 3")

If you're not interested in the return value of a function, you can call a function just as you would call a Sub procedure. You omit the parentheses, list the arguments, and do not assign the function to a variable, as shown in the following example.

MsgBox "Task Completed!", 0, "Task Box"

Note   If you include parentheses in the preceding example, the statement causes a syntax error.

Passing named arguments

A statement in a Sub or Function procedure can pass values to called procedures by using named arguments. You can list named arguments in any order. A named argument is always followed by a colon and an equal sign (:=), and then the argument value.

The following example calls the MsgBox function by using named arguments; it ignores the return value.

MsgBox Title:="Task Box", Prompt:="Task Completed!"

The following example calls the MsgBox function by using named arguments; it assigns the return value to the variable answer3.

answer3 = MsgBox(Title:="Question 3", _

Prompt:="Are you happy with your salary?", Buttons:=4)


Calling procedures in other workbooks

Before you can call procedures in another workbook, you must establish a reference to that workbook (a connection between your workbook and the workbook containing the procedure you want to call).

To establish a reference to another workbook

1.	With a Visual Basic module active, click References on the Tools menu.

2.	In the Available References box, click the name of the workbook that contains the procedure you want to call.

If the workbook name does not appear in the list, click the Browse button to add the name to the list.

3.	Select the check box next to the name of the workbook.

Once a reference has been established, you can call any public procedure in the referenced workbook. The referenced workbook also appears in the Libraries list in the Object Browser when the referencing workbook is active.

Notes

•	Visual Basic does not allow cyclic references. That is, if workbook A references workbook B, workbook B cannot reference workbook A.

•	Visual Basic does allow indirect references. That is, if workbook A references workbook B, which in turn references workbook C, workbook A can call procedures in workbook C by specifying the workbook name in the calling statement. Any combination of direct and indirect references that causes a cyclic reference is not allowed.


Calling procedures with the same name

You can call a procedure located in any module in the same workbook as the active module just as you would call a procedure in the active module. However, if two or more modules contain a procedure with the same name, you need to specify a module name in the calling statement, as shown in the following example.

Sub Main()

[Module1].MyProcedure

End Sub

If you give the same name to two different procedures in two different workbooks, you must specify a workbook name when you call that procedure. For example, the following procedure calls the Main procedure in the module My Module in the workbook MYBOOK.XLS.

Sub Main()

[MyBook.xls].[My Module].Main

End Sub

Tips for calling procedures

•	To protect a procedure from being called by other workbooks, declare the procedure as Private or declare the entire module as Option Private Module.

•	If you rename a module or workbook, be sure to change the module or workbook name wherever it appears in calling statements; otherwise, Visual Basic will not be able to find the called procedure. You can use the Replace command (Edit menu) to find and replace text in a module.

•	To avoid naming conflicts among referenced workbooks, give your procedures unique names. By avoiding naming conflicts, you can call a procedure without specifying which workbook or module it's in.


Most frequently asked Visual Basic questions

  How do I get a copy of the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide?

Visual Basic concepts

  What are objects, properties, and methods?

  How do I find out which property or method I need?

  What is an object variable, and how do I use one?

  What is meant by the scope of a variable?

  What is meant by the lifetime of a variable?

  What is a Variant?

  How do I work with arrays?

  What are all the looping and conditional statements in Visual Basic?

  What is the With statement?

Procedures and modules

  How do I continue a statement to the next line?

  How do I connect strings in Visual Basic?

  What is an OnEvent procedure?

  What are the limitations of a user-defined worksheet function?

  How do I display a custom dialog box?

  How do I create an edit box with a password?

  How do I call a Sub procedure or Function procedure located in a module in another workbook?

  How do I share variables between two workbooks?

  What is an add-in application, and where can I learn more about add-ins?

  How do I print the code in my module?

Microsoft Excel features

  How do I call a built-in Microsoft Excel worksheet function in Visual Basic?

  How do I find out what the worksheet functions are and what they do?

  How do I find out the Visual Basic equivalent for a Microsoft Excel 4.0 macro function or command?

  How do I display a built-in Microsoft Excel dialog box?

  How do I manipulate the active cell?

  How do I refer to a cell or range on a worksheet in Visual Basic?

  How do I reference a named range in Visual Basic?

  What is a good way to cycle through a range of cells using Visual Basic?

  How do I turn off screen updating?

  How do I work with a chart in Visual Basic?

  Where can I get information about how to connect to a database using Visual Basic?

Code errors

  How do I use the Debug window?

  How do I prevent error messages from being displayed?

  How do I stop a macro caught in an endless loop?

  Why does my procedure fail when I use the Select method?

  Why does my procedure fail when I try to run it from the module?

  How do I use parentheses correctly in a Visual Basic function?


How do I continue a statement to the next line?

To continue a statement from one line to the next, type a space followed by the underscore character (_). You cannot break statements in the middle of a keyword value. You can break a line at an operator, list separator, or period, as shown in the following statement.

Workbooks("MyBook.xls").Worksheets("Sheet1") _

.Range("A1:B5").Value = _

var1 + 3.14159


How do I turn off screen updating?

To turn off screen updating, include the following statement in a procedure.

Application.ScreenUpdating = False


How do I prevent error messages from being displayed?

To turn off automatic syntax checking in a module, click Options on the Tools menu. On the Module General tab, clear the Display Syntax Errors check box.

To prevent error messages from being displayed while a procedure is running, include the following statement in the procedure.

Application.DisplayAlerts = False


How do I find out which property or method I need?

An easy way to find out what method or property to use is to record actions similar to the ones you want your procedure to perform and then examine the recorded code. For more information, see Recording a macro to generate code.


How do I find out what the worksheet functions are and what they do?

With a worksheet active, click  [image]. Select the category and then the function you're interested in. A description is displayed at the bottom of the dialog box.


How do I stop a macro caught in an endless loop?

Press either ESC or CTRL+BREAK. To debug the macro, you may need to comment out any statements inside the loop that use a message box or an input box. If you've been relying on the dialog box to display the value of a variable, you can use Debug.Print to display the value in the Debug window instead. For more information about Debug.Print and the Debug window, see How to use the Debug window.


Why does my procedure fail when I try to run it from the module?

When you run your procedure from a module, the module is the active sheet. Some properties (such as ActiveCell) and methods (such as Select) require a worksheet to be the active sheet. For information about ways to reference cells without using the Select method, see How to reference cells and ranges. Unqualified methods such as Range and Cells must be invoked from the active worksheet. If you want to invoke these methods from a module, you must qualify them explicitly.


How do I connect strings in Visual Basic?

In Visual Basic, the concatenation operator is an ampersand (&). Be sure to include a space before and after the ampersand. The following example concatenates a string and a variable to display in a simple message box.

Sub Message()

MsgBox "The answer is " & myVariable

End Sub


How do I get a copy of the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide?

The Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide (Microsoft Press, 1995) is available wherever computer books are sold and directly from Microsoft Press. ISBN 1-55615-819-X. Credit card orders: 1-800-MSPRESS (1-800-677-7377). CompuServe: GO MSP.

Information from the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide is also available online on the Microsoft Network. If you are a member of the Microsoft Network, you can connect to the Microsoft forum by clicking here


How do I create an edit box with a password?

To create password functionality for an edit box, select the edit box on the dialog sheet, and then click Object on the Format menu. Select the Password Edit check box.


How do I print the code in my module?

Switch to the module sheet, and then click  [image].


What is an add-in application, and where can I learn more about add-ins?

An add-in application is a workbook saved in the add-in format. When you save a workbook as an add-in, Microsoft Excel compiles the code and protects it from being opened or modified by anyone else. Add-ins are an easy way to distribute your macros, user-defined functions, or complex macro applications to users. For information about how to create, transport, and use add-in applications, see the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide.


Recording into the correct module

The first time you record after creating or opening a workbook, the macro recorder inserts a new module sheet in that workbook. Each macro you record while the workbook is active is recorded into this module. By default, the macro recorder keeps a separate Visual Basic module for each open workbook. However, if you add other Visual Basic modules to your workbook, you can specify the module into which the recorder should record.

1.	Activate the Visual Basic module into which you want to record.

2.	Click outside any existing procedures.

3.	On the Tools menu, point to Record Macro, and then click Mark Position For Recording.

The next time you click Record New Macro, the macro recorder will record at the point you marked.

Recording into a new workbook

To record a macro into a new module in a new workbook, click Options in the Record New Macro dialog box (Tools menu, Record Macro submenu, Record New Macro command), and then click New Workbook under Store In. You must set this option each time you record a macro.

Recording into the Personal macro workbook

To record a macro that you always want available, click Options in the Record New Macro dialog box, and then click Personal Macro Workbook. The Personal macro workbook is a hidden workbook that is always open. Remember to give macros you record into this workbook meaningful names and descriptions. You may also want to assign frequently used macros to menu items or shortcut keys. To unhide the Personal macro workbook, click Unhide on the Window menu.

Tips for using recorded macros

•	If you often record to discover method and property names or to experiment with features, you can keep a workbook open just for this purpose. When you have refined your macros, you can copy them into another Visual Basic module.

•	You can move or copy module sheets between workbooks. If you do this, be sure your references are complete.

•	You can copy and paste code fragments from one module to another.

•	You can rename your Visual Basic module. Double-click the module tab to rename the sheet.


Recording into an existing procedure

You can record one or more statements into any open Visual Basic module. Unlike the Record New Macro command (Tools menu, Record Macro submenu), this technique does not enclose the recorded statements within a Sub...End Sub statement.

1.	Activate the Visual Basic module into which you want to record one or more statements.

2.	Click where you want to add the code.

3.	On the Tools menu, point to Record Macro, and then click Mark Position For Recording.

4.	Activate the sheet from which you want to record.

5.	On the Tools menu, point to Record Macro, and then click Record At Mark.

6.	Carry out the actions you want to record.

7.	Click [image].


Revising recorded Visual Basic macros

The macro recorder is a great tool for discovering the Visual Basic methods and properties you want to use. But there are limitations to recording macros. You cannot record the following:

•	Conditional branches

•	Looping structures

•	Calculated selections and references

•	Some built-in functions and dialog boxes

•	Custom dialog boxes

To enhance your macros, you need to edit the code recorded into your module. For basic information about editing in a module, see Working in a module.

Removing the Select method and the Selection property

The recorder often records the Select method and the Selection property. For example, the following macro was recorded while an oval was being drawn.

Sub Macro1()

ActiveSheet.Ovals.Add(46.5, 24, 51.75, 18).Select

Selection.Interior.ColorIndex = xlNone

End Sub

To run the macro from any sheet and have the oval appear on Sheet1, you need to refer to the exact object you are manipulating. You could rewrite the macro as follows:

Sub MyMacro()

Worksheets("Sheet1").Ovals.Add(46.5, 24, 51.75, 18) _

.Interior.ColorIndex = xlNone

End Sub

To have the oval appear on Sheet1 (not the active sheet), you need to replace the ActiveSheet property with the Worksheets method. The Select method and the Selection property require the worksheet to be active, so you should eliminate them both; this is done by combining the two statements that were recorded originally. As a result, the code is simplified and the macro can be run from any sheet.

Removing the ActiveCell property

The recorder often records the ActiveCell property, as shown in the following example.

Sub Macro1()

ActiveCell.FormulaR1C1 = "Cost per Unit"

Selection.Font.Bold = True

Selection.Columns.AutoFit

End Sub

The macro works when it's run from the active cell on a worksheet. You could rewrite the macro as follows to pass the Sub procedure MyMacro a cell reference as an argument. MyMacro does not require the worksheet to be active.

Sub Main()

MyMacro (Worksheets("Sheet1").Range("A1"))

End Sub

Sub MyMacro(myCell As Range)

With myCell

.FormulaR1C1 = "Cost per Unit"

.Font.Bold = True

.Columns.AutoFit

End With

End Sub

Removing unnecessary arguments

The recorder may record all the arguments of a method, even if you want to change only one or two. You can remove the unnecessary arguments from statements you record. The following recorded macro includes all the arguments for the Find method.

Sub Macro4()

Cells.Find(What:="Total", After:=ActiveCell, LookIn:=xlFormulas, _

LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext _

, MatchCase:=False).Activate

End Sub

Because you changed only one argument, you can rewrite the macro as follows:

Sub MyMacro()

Cells.Find(What:="Total").Activate

End Sub


Creating a new workbook

To create a new workbook in Visual Basic, you use the Add method. The following procedure creates a new workbook. Microsoft Excel automatically names the workbook BookN, where N is the next available number. The new workbook becomes the active workbook.

Sub AddOne()

Workbooks.Add

End Sub

A better way to create a new workbook is to assign it to an object variable. In the following example, the Workbook object returned by the Add method is assigned to an object variable, newBook. Next, several properties of newBook are set. You can easily control the new workbook using the object variable.

Sub AddNew()

Set newBook = Workbooks.Add

With newBook

.Title = "1995 Sales"

.Subject = "Sales"

.SaveAs filename:="95Sales.xls"

End With

End Sub


Opening a workbook

When you open a workbook using the Open method, it becomes a member of the Workbooks collection. The following procedure opens a workbook named MyBook.xls located in the folder named "MyFolder" on drive C.

Sub OpenUp()

Workbooks.Open("C:\MyFolder\MyBook.xls")

End Sub


Activating a workbook

Activating a workbook using the Activate method puts the workbook in the active window. The following procedure activates the open workbook named "MyBook.xls."

Sub MakeActive()

Workbooks("MyBook.xls").Activate

End Sub


Referring to sheets by name

You can identify sheets by name using the Worksheets, Charts, Modules, and DialogSheets methods. The following statements activate various sheets in the active workbook.

Worksheets("Sheet1").Activate

Charts("Chart1").Activate

Modules("Module1").Activate

DialogSheets("Dialog1").Activate

You can use the Sheets method to return a worksheet, chart, module, or dialog sheet; the Sheets collection contains all of these. The following example activates the sheet named "Chart1" in the active workbook.

Sub ActivateChart()

Sheets("Chart1").Activate

End Sub

Note   Charts embedded in a worksheet are members of the ChartObjects collection, whereas charts that exist on their own sheets belong to the Charts collection. For more information, see Working with charts.


Referring to sheets by index number

An index number is a sequential number assigned to a sheet, based on the position of its sheet tab (counting from the left) among sheets of the same type. The following procedure uses the Worksheets method to activate worksheet one in the active workbook.

Sub FirstOne()

Worksheets(1).Activate

End Sub

If you want to work with all types of sheets (worksheets, charts, modules, and dialog sheets), use the Sheets method. The following procedure activates sheet four in the workbook.

Sub FourthOne()

Sheets(4).Activate

End Sub

Note   The index order can change if you move, add, or delete sheets.


Referring to more than one sheet

You use the Array function to identify a group of sheets. The following example selects three sheets in the active workbook.

Sub Several()

Worksheets(Array("Sheet1", "Sheet2", "Sheet4")).Select

End Sub


How to reference cells and ranges

A common task when using Visual Basic is to specify a cell or range of cells and then do something with it, such as enter a formula or change the format. You can usually do this in one statement that identifies the range and also changes a property or applies a method.

A Range object in Visual Basic can be either a single cell or a range of cells. The following topics show the most common ways to identify and work with Range objects.

Which way do you want to reference cells?

Referring to cells and ranges using A1 notation

Referring to cells using index numbers

Referring to rows and columns

Referring to cells using shortcut notation

Referring to named ranges

Referring to cells relative to other cells

Referring to cells using a Range object

Referring to all the cells on the worksheet

Referring to multiple ranges


Referring to cells and ranges using A1 notation

You can refer to a cell or range of cells in the A1 reference style by using the Range method. The following Sub procedure changes the format of cells A1:D5 to bold.

Sub FormatRange()

Workbooks("Book1").Sheets("Sheet1").Range("A1:D5") _

.Font.Bold = True

End Sub

The following table illustrates some A1-style references using the Range method.

Reference	Meaning

Range("A1")	Cell A1

Range("A1:B5")	Cells A1 through B5

Range("C5:D9,G9:H16")	A multiple-area selection

Range("A:A")	Column A

Range("1:1")	Row one

Range("A:C")	Columns A through C

Range("1:5")	Rows one through five

Range("1:1,3:3,8:8")	Rows one, three, and eight

Range("A:A,C:C,F:F")	Columns A, C, and F


Referring to cells using index numbers

You can use the Cells method to refer to a single cell by using row and column index numbers. This method returns a Range object that represents a single cell. In the following example, Cells(6,1) returns cell A6 on Sheet1. The Value property is then set to 10.

Sub EnterValue()

Worksheets("Sheet1").Cells(6, 1).Value = 10

End Sub

The Cells method works well for looping through a range of cells, because you can substitute variables for the index numbers, as shown in the following example.

Sub CycleThrough()

Dim counter As Integer

For counter = 1 To 20

Worksheets("Sheet1").Cells(counter, 3).Value = counter

Next counter

End Sub

Note   If you want to change the properties of or apply a method to a range of cells all at once, use the Range method. For more information, see Referring to cells using A1 notation.


Referring to rows and columns

Use the Rows method or the Columns method to work with entire rows or columns. These methods return a Range object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property of the Font object for the range is then set to True.

Sub RowBold()

Worksheets("Sheet1").Rows(1).Font.Bold = True

End Sub

The following table illustrates some row and column references using the Rows and Columns methods.

Reference	Meaning

Rows(1)	Row one

Rows	All the rows on the worksheet

Columns(1)	Column one

Columns("A")	Column one

Columns	All the columns on the worksheet

To work with several rows or columns at the same time, create an object variable and use the Union method, combining multiple calls to the Rows or Columns method. The following example changes the format of rows one, three, and five on worksheet one in the active workbook to bold.

Sub SeveralRows()

Worksheets("Sheet1").Activate

Dim myUnion As Range

Set myUnion = Union(Rows(1), Rows(3), Rows(5))

myUnion.Font.Bold = True

End Sub


Referring to cells using shortcut notation

You can use either the A1 reference style or a named range within brackets as a shortcut for the Range method. You don't have to type the word "Range" or use quotation marks, as shown in the following examples.

Sub ClearRange()

Worksheets("Sheet1").[A1:B5].ClearContents

End Sub

Sub SetValue()

[MyRange].Value = 30

End Sub


Referring to named ranges

Ranges are easier to identify by name than by A1 notation. To name a selected range, click the name box at the left end of the formula bar, type a name, and then press ENTER.

Referring to a named range

The following example refers to the range named "MyRange" in the workbook named "MyBook.xls."

Sub FormatRange()

Range("MyBook.xls!MyRange").Font.Italic = True

End Sub

The following example refers to the worksheet-specific range named "Sheet1!Sales" in the workbook named "Report.xls."

Sub FormatSales()

Range("[Report.xls]Sheet1!Sales").BorderAround weight:=xlthin

End Sub

To select a named range, use the GoTo method, which activates the workbook and the worksheet and then selects the range.

Sub ClearRange()

Application.Goto Reference:="MyBook.xls!MyRange"

Selection.ClearContents

End Sub

The following example shows how the same procedure would be written for the active workbook.

Sub ClearRange()

Application.Goto Reference:="MyRange"

Selection.ClearContents

End Sub

Looping through cells in a named range

The following example loops through each cell in a named range by using a For Each...Next loop. If the value of any cell in the range exceeds the value of limit, the cell color is changed to yellow.

Sub ApplyColor()

Const limit As Integer = 25

For Each c In Range("MyRange")

If c.Value > limit Then

c.Interior.ColorIndex = 27

End If

Next c

End Sub


Referring to cells relative to other cells

A common way to work with a cell relative to another cell is to use the Offset method. In the following example, the contents of the cell that's one row down and three columns over from the active cell on the active worksheet are formatted as double-underlined.

Sub Underline()

ActiveCell.Offset(1, 3).Font.Underline = xlDouble

End Sub

Note  You can record macros that use the Offset method instead of absolute references. On the Tools menu, point to Record Macro, and then click Use Relative References.

To loop through a range of cells, use a variable with the Cells method in a loop. The following example fills the first 20 cells in the third column with values between 5 and 100, incremented by 5. The variable counter is used as the row index for the Cells method.

Sub CycleThrough()

Dim counter As Integer

For counter = 1 To 20

Worksheets("Sheet1").Cells(counter, 3).Value = counter * 5

Next counter

End Sub


Referring to cells using a Range object

If you set an object variable to a Range object, you can easily manipulate the range by using the variable name.

The following procedure creates the object variable myRange and then assigns the variable to range A1:D5 on Sheet1 in the active workbook. Subsequent statements modify properties of the range by substituting the variable name for the range object.

Sub Random()

Dim myRange As Range

Set myRange = Worksheets("Sheet1").Range("A1:D5")

myRange.Formula = "=RAND()"

myRange.Font.Bold = True

End Sub

Note   You can create object variables for any Microsoft Excel object. For more information about creating object variables, see Using object variables in Microsoft Excel.


Referring to all the cells on the worksheet

When you apply the Cells method to a worksheet without specifying an index number, the method returns a Range object that represents all the cells on the worksheet. The following Sub procedure clears the contents from all the cells on Sheet1 in the active workbook.

Sub ClearSheet()

Worksheets("Sheet1").Cells.ClearContents

End Sub


Referring to multiple ranges

Using the appropriate method, you can easily refer to multiple ranges. Use the Range and Union methods to refer to any group of ranges; use the Areas method to refer to the group of ranges selected on a worksheet.

Using the Range method

You can refer to multiple ranges with the Range method by putting commas between two or more references. The following example clears the contents of three ranges on Sheet1.

Sub ClearRanges()

Worksheets("Sheet1").Range("C5:D9,G9:H16,B14:D18").ClearContents

End Sub

Named ranges make using the Range method to work with multiple ranges easier. The following example works when all three named ranges are on the same sheet.

Sub ClearNamed()

Range("MyRange, YourRange, HisRange").ClearContents

End Sub

Using the Union method

You can combine multiple ranges into one Range object using the Union method. The following example creates a Range object called myMultipleRange, defines it as the ranges A1:B2 and C3:D4, and then formats the combined ranges as bold.

Sub MultipleRange()

Dim r1, r2, myMultipleRange As Range

Set r1 = Sheets("Sheet1").Range("A1:B2")

Set r2 = Sheets("Sheet1").Range("C3:D4")

Set myMultipleRange = Union(r1, r2)

myMultipleRange.Font.Bold = True

End Sub

Using the Areas method

You can use the Areas method to refer to the selected range or to the collection of ranges in a multiple-area selection. The following procedure counts the areas in the selection. If there is more than one area, a warning message is displayed.

Sub FindMultiple()

If Selection.Areas.Count > 1 Then

MsgBox "Cannot do this to a multiple selection."

End If

End Sub


Selecting and activating cells

When you work with Microsoft Excel, you usually select a cell or cells and then perform an action, such as formatting the cells or entering values in them. In Visual Basic, it is usually not necessary to select cells before modifying them.

For example, if you want to enter a formula in cell D6 using Visual Basic, you don't need to select the range D6. You just need to return the Range object and then set the Formula property to the formula you want, as shown in the following example.

Sub EnterFormula()

Worksheets("Sheet1").Range("D6").Formula = "=SUM(D2:D5)"

End Sub

For examples of using other methods to control cells without selecting them, see How to reference cells and ranges.

Using the Select method and the Selection property

The Select method activates sheets and objects on sheets; the Selection property returns an object that represents the current selection on the active sheet in the active workbook. Before you can use the Selection property successfully, you must activate a workbook, activate or select a sheet, and then select a range (or other object) using the Select method.

The macro recorder will often create a macro that uses the Select method and the Selection property. The following Sub procedure was created using the macro recorder, and it illustrates how Select and Selection work together.

Sub Macro1()

Sheets("Sheet1").Select

Range("A1").Select

ActiveCell.FormulaR1C1 = "Name"

Range("B1").Select

ActiveCell.FormulaR1C1 = "Address"

Range("A1:B1").Select

Selection.Font.Bold = True

End Sub

The following example accomplishes the same task without activating or selecting the worksheet or cells.

Sub Labels()

With Worksheets("Sheet1")

.Range("A1") = "Name"

.Range("B1") = "Address"

.Range("A1:B1").Font.Bold = True

End With

End Sub

Selecting cells on the active worksheet

If you use the Select method to select cells, be aware that Select works only on the active worksheet. If you run your Sub procedure from the module, the Select method will fail unless your procedure activates the worksheet before using the Select method on a range of cells. For example, the following procedure copies a row from Sheet1 to Sheet2 in the active workbook.

Sub CopyRow()

Worksheets("Sheet1").Rows(1).Copy

Worksheets("Sheet2").Select

Worksheets("Sheet2").Rows(1).Select

Worksheets("Sheet2").Paste

End Sub

Activating a cell within a selection

You can use the Activate method to activate a cell within a selection. There can be only one active cell, even when a range of cells is selected. The following procedure selects a range and then activates a cell within the range without changing the selection.

Sub MakeActive()

Worksheets("Sheet1").Activate

Range("A1:D4").Select

Range("B2").Activate

End Sub


Working with the active cell

The ActiveCell property returns a Range object that represents the cell that is active. You can apply any of the properties or methods of a Range object to the active cell, as in the following example.

Sub SetValue()

Worksheets("Sheet1").Activate

ActiveCell.Value = 35

End Sub

Note   You can work with the active cell only when the worksheet that it is on is the active sheet.

Moving the active cell

You can use the Activate method to designate which cell is the active cell. For example, the following procedure makes B5 the active cell and then formats it as bold.

Sub SetActive()

Worksheets("Sheet1").Activate

Worksheets("Sheet1").Range("B5").Activate

ActiveCell.Font.Bold = True

End Sub

Note   To select a range of cells, use the Select method. To make a single cell the active cell, use the Activate method.

You can use the Offset method to move the the active cell. The following procedure inserts text into the active cell in the selected range and then moves the active cell one cell to the right without changing the selection.

Sub MoveActive()

Worksheets("Sheet1").Activate

Range("A1:D10").Select

ActiveCell.Value = "Monthly Totals"

ActiveCell.Offset(0, 1).Activate

End Sub

Selecting the cells surrounding the active cell

The CurrentRegion property returns a range of cells bounded by blank rows and columns. In the following example, the selection is expanded to include the cells adjoining the active cell that contain data. This range is then formatted with the Currency style.

Sub Region()

Worksheets("Sheet1").Activate

ActiveCell.CurrentRegion.Select

Selection.Style = "Currency"

End Sub


Working with 3-D ranges

If you are working with the same range on more than one sheet, use the Array function to specify two or more sheets to select. The following example formats the border of a 3-D range of cells.

Sub FormatSheets()

Sheets(Array("Sheet2", "Sheet3", "Sheet5")).Select

Range("A1:H1").Select

Selection.Borders(xlBottom).LineStyle = xlDouble

End Sub

The following example applies the FillAcrossSheets method to transfer the formats and any data from the range on Sheet2 to the corresponding ranges on all the worksheets in the active workbook.

Sub FillAll()

Worksheets("Sheet2").Range("A1:H1") _

.Borders(xlBottom).LineStyle = xlDouble

Worksheets.FillAcrossSheets (Worksheets("Sheet2") _

.Range("A1:H1"))

End Sub


Recording a macro to generate code

If you are unsure of which Visual Basic method or property to use, you can record a short macro to generate the code you need. After you have created some code, you can modify it to do exactly what you want.

Tips for using the macro recorder

•	Display the Visual Basic toolbar so that you can use the Record, Run, and Stop buttons instead of the menu.

•	Record short procedures you can call and use from your main procedure. This makes your code easier to manage, reuse, and debug.

•	Turn on Use Relative References to make Microsoft Excel keep track of cell references relative to the active cell as it records. You can run the resulting macro from anywhere on your worksheet. For information about using this command, see Record a macro.

•	Use Record At Mark to record code into an existing procedure. For information about using this command, see Recording into an existing procedure.


Getting online Help for Visual Basic

There are many ways to access online Help for answers to Visual Basic questions and for information about Visual Basic keywords. The following are a few of the most common and useful ways of accessing Help.

Press F1 in a Visual Basic module

While you are working in a module, you can go directly to online Help on a method, property, function, statement, or object by clicking the keyword in a line of code and then pressing F1.

Browse the object hierarchy

You can display a Help topic that illustrates the entire Microsoft Excel object model by clicking Microsoft Excel Object Model under Microsoft Excel Visual Basic Reference in the Help contents. Click an object to display its Help topic. In the object topic, you can click more graphics to display related object topics.

The object model shows graphics only for objects. To find the methods or properties for a particular object, click either Methods or Properties at the top of the object topic.

You can also use the Object Browser to see the list of an object's methods and properties. For information about using the Object Browser, see Using the Object Browser.

Ask the Answer Wizard

The Answer Wizard makes it easy to find the topics you are looking for. Just type your query, and then select one of the topics the Answer Wizard suggests. The more specific your query is, the more specific the suggested topics will be. An example of a specific query is "How do I program my chart to become a pie chart?"

On the Answer Wizard tab in the Help Topics dialog box, look under Programming And Language Reference for topics that relate to Visual Basic. The How Do I and Tell Me About areas list related topics for the corresponding Microsoft Excel features.

Use the Contents tab

The Help Topics dialog box contains several tabs. Use the Contents tab to view alphabetic lists of objects, methods, properties, functions, and statements. You can also access the Getting Started topics from the Contents tab.

Tips

•	Use ALT+TAB or the Taskbar to switch between your application and online Help. If you leave online Help active, you can immediately return to the last topic you were viewing.

•	Use the shortcut menu to copy selected text, change the font size, print, annotate, or keep the Help window on top.


Copying Visual Basic examples

You can copy examples (or any text) from a Help topic by using the right mouse button to select the text you want to copy, clicking Copy on the shortcut menu, activating Microsoft Excel, and then pasting the example into your module.

Try copying the following example into a module.

Sub Squared()

answer = Application.InputBox(Prompt:="Type a number", Type:=1)

answer = Sqr(answer)

MsgBox "The square root is " & answer

End Sub

Tip   You can also press CTRL+C to copy a selected example in a Help window. Press CTRL+V to paste the example into the module.


Using the Object Browser

The Object Browser allows you to browse through all the available Visual Basic objects and see their properties and methods. You can easily display online Help as you browse.

To locate a method or property in the Object Browser

1.	Activate a module.

2.	On the View menu, click Object Browser.

3.	In the Libraries/Workbooks box, click Microsoft Excel library or another library.

4.	In the Objects/Modules box, click the object you are interested in.

5.	In the Methods/Properties box, click the method or property you want.

You can click [image] to see online Help for the selected item.

When you have located the method or property you want, you can paste its syntax into the active module.

To paste method syntax or property syntax into a module

1.	Click in a module where you want to paste the syntax.

2.	Locate the method or property in the Object Browser.

3.	Click Paste.

The syntax, including all the named arguments, appears in your module.


Understanding objects, properties, and methods

Objects are the fundamental building block of Visual Basic; nearly everything you do in Visual Basic involves manipulating objects. Every element of Microsoft Excel --- workbooks, worksheets, charts, cells, and so on --- can be represented by an object in Visual Basic. By creating procedures that apply the methods and control the properties of these objects, you automate tasks in Microsoft Excel.

What are objects?

An object represents an element of Microsoft Excel, such as a workbook, a worksheet, a chart, or a range of cells. In Visual Basic code, you must identify an object before you can apply one of the object's methods or change the value of one of its properties.

What are collections?

A collection is an object that contains several other objects, usually of the same type. The Workbooks object contains all the open Workbook objects.

You use the Workbooks method to return an individual member of the Workbooks collection. Working with a collection is like working with an array; you can identify an item within it by enclosing a name or number in parentheses. For example, in the following procedure, Workbooks(1) identifies the first open Workbook object, and the Close method closes it.

Sub CloseFirst()

Workbooks(1).Close

End Sub

The following procedure uses a name (specified as a string) to identify a Workbook object.

Sub CloseBook()

Workbooks("MyBook.xls").Close

End Sub

Note   You use the Workbooks and Worksheets methods to identify an individual workbook or worksheet. You never use the word "Workbook" or "Worksheet" in Visual Basic to denote a Workbook or Worksheet object.

You can also manipulate the entire collection of objects. For example, the following procedure closes all the open workbooks.

Sub CloseAll()

Workbooks.Close

End Sub

Drilling down to an object

To return an object, you must "drill down" through the Microsoft Excel object hierarchy. For example, the following procedure deletes the first worksheet in the workbook named "Book6.xls."

Sub DeleteOne()

Application.Workbooks("Book6.xls").Worksheets(1).Delete

End Sub

The Application property returns the Application object. The Workbooks method of the Application object returns the single workbook object that refers to Book6.xls. Then the Worksheets method of the Workbook object returns the first Worksheet object in Book6.xls. Finally, the Delete method is applied to the Worksheet object.

As you can see, you always use a method or property to drill down to an object. That is, you return an object by applying a method or property to an object above it in the object hierarchy. After you return the object you want, you can apply the methods and control the properties of that object. To review the hierarchy of objects, see Microsoft Excel Objects. For more information about using methods and properties to drill down to an object, see "Returning objects using methods and properties" later in this topic.

Tips

•	If your procedure fails, you may have left out part of the object hierarchy. For example, when you try to reference a Range object without specifying the Worksheet object that contains it, Visual Basic displays the message "Range method of Application class failed."

•	In many cases, you don't need to use the Application object in your Visual Basic statements. To find out whether the Application object is required for a particular method or property, see the online Help topic for that method or property.

What are methods?

A method is an action that an object can perform. For instance, Close is a method of the Workbook object.

The following procedure uses the Add method to add a new worksheet to the active workbook. Add is a method of the Worksheets collection object, because it adds a new worksheet to the collection of worksheets.

Sub AddSheet()

Worksheets.Add

End Sub

What are properties?

A property is usually an attribute of an object that defines one of the object's characteristics (such as size, color, or screen location) or an aspect of its behavior (such as whether it is enabled or visible). To change the characteristics of an object, you change the values of its properties. Properties never have arguments.

To set the value of a property, follow the reference to an object with a period, the property name, an equal sign, and the new property value. For example, the following procedure changes the name of a worksheet by setting the Name property.

Sub ChangeName()

Workbooks("MyBook.xls").Worksheets("Sheet1") _

.Name = "MyWorksheet"

End Sub

Some properties cannot be set. The Help topic for a property indicates whether that property can be set (read-write) or can only be read (read-only).

You can retrieve information about an object by returning the value of one of its properties. The following procedure places the formula for cell C5 in the variable myFormula and then displays the contents of the variable in a dialog box by using the MsgBox function. Formula is a property of the Range object.

Sub GetFormula()

myFormula = Worksheets("Sheet1").Range("C5").Formula

MsgBox myFormula

End Sub

Returning objects using methods and properties

A method or property that returns an object is called an accessor.

In the following procedure, the Workbooks method returns a specific Workbook object. The Workbooks method is an accessor. The Activate method is then applied to the Workbook object.

Sub MakeActive()

Workbooks("MyBook.xls").Activate

End Sub

An accessor is typically followed by one or more arguments in parentheses. In the following example, the Worksheets method returns the Worksheet object named "Sheet1" because the name is specified as the argument. The Cells method returns a Range object containing the cell A1. Finally, the ClearContents method is applied to the range.

Sub ClearCell()

Worksheets("Sheet1").Cells(1, 1).ClearContents

End Sub

Properties usually return values such as numbers, text, or True or False, but some properties return objects. Some examples of accessor properties are ActiveCell, ActiveWindow, ActiveSheet, Selection, Font, Interior, and Border. For instance, the ActiveWorkbook property returns an object that represents the active workbook (a Workbook object). The following procedure uses the Close method to close the active workbook without saving changes.

Sub CloseActive()

ActiveWorkbook.Close saveChanges:=False

End Sub

Getting Help on objects, methods, and properties

You return an object by applying a method or property to the object above it in the hierarchy. You must drill down through the hierarchy to return the object you want. Use Help to find out which properties and methods you can use for an object and which objects appear above or below a given object in the hierarchy. To display online Help while you are in a module, click in a keyword and then press F1.


Understanding scope

Scope refers to the accessibility of a variable, constant, or procedure --- that is, its ability to be "seen" by other procedures. For example, a variable that is declared inside a procedure is not available to any other procedure in the same module or workbook. There are three scoping levels: procedure, private, and public.

Procedure scope

A variable or constant defined within a procedure is not recognized outside that procedure. Only the procedure that contains the variable declaration can use it. In the following example, the procedure MyProg displays a message box that contains the string "Hello!". The procedure YourProg displays a blank message box because the variable myMsg is not defined outside the MyProg procedure.

Sub MyProg()

Dim myMsg As String

myMsg = "Hello!"

MsgBox myMsg

End Sub

Sub YourProg()

MsgBox myMsg

End Sub

Private scope

You can define variables and constants outside a procedure. These are declared at the top of the module in the declarations section. By default, variables declared with the Dim statement in the declarations section are scoped as private (available only to the procedures in that module). However, you can use Private instead of Dim to make the scope obvious in your code.

In the following example, the string variable myMsg is available to the procedures MyProg and YourProg and any other procedures in the module.

Dim myMsg As String

Sub MyProg()

myMsg = "Hello!"

End Sub

Sub YourProg()

MsgBox myMsg

End Sub

Procedures themselves have scope and are available by default to all the modules in a workbook. If you declare a procedure as Private, it can be called by any procedure in the same module, but it cannot be called from any other module. In addition, you cannot run a Private procedure as a stand-alone macro, nor can you assign it to a menu item, shortcut key, toolbar button, or control.

In the following example, MyPriv cannot be called from another module, but it can be called by GetPrivate.

Private Sub MyPriv()

MsgBox "Message from MyPriv"

End Sub

Sub GetPrivate()

MyPriv

End Sub

Note   To limit the scope of a procedure to the workbook in which it is declared, make the module private by adding the Option Private Module statement to the declarations section.

Public scope

By default, procedures are public (available to all modules in the workbook) unless they are declared as Private. A private procedure is available only to the module in which it resides.

For a variable or constant to be seen by all the modules in a workbook, it must be declared as Public in the declarations section at the top of a module. In the following example, the string variable myMsg can be used by any procedure in any module in the workbook.

Public myMsg As String

You can use public procedures, variables, and constants from other workbooks, but you must first set up a reference to the workbook. For information about referencing other workbooks, see Calling procedures in other workbooks.


Lifetime of variables

The time during which a variable retains its value is known as its lifetime.

Usually, a procedure-level variable is given a default value each time the procedure is called (its lifetime is limited to the duration of the procedure). Local variables declared with the Static keyword exist the entire time that the workbook in which they are declared is open; that is, the variables retain their values between calls to the procedure.

In the following example, the values of the three variables are preserved and displayed as default values the next time the user runs the program.

Sub LoanCalc()

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")

End Sub

If you include the Static keyword before a Sub or Function statement, the values of all the local (procedure-level) variables in the procedure are preserved between calls. For example, the first four lines of the preceding example could be written as follows.

Static Sub LoanCalc()

Dim loanAmt

Dim loanInt

Dim loanTerm

Note   After you edit a module, the next time you run a procedure Visual Basic recompiles all modules in the workbook and resets all variables. If you need to preserve values when the workbook is compiled or saved, use a hidden worksheet to store the values.


How to interpret Visual Basic syntax

The syntax found in the Help topic for a Visual Basic method, statement, or function shows all the elements you need to use the method, statement, or function correctly. The examples in this topic explain how to interpret the most common syntax elements.

Syntax for the Activate method

object.Activate

In the Activate method syntax, the italic word "object" is a place holder for information you supply --- in this case, the code that returns an object. Words that are bold should be typed exactly as they appear. For example, the following procedure activates the second window in the active document.

Sub MakeActive()

Windows(2).Activate

End Sub

Syntax for the MsgBox function

MsgBox(prompt[,buttons][,title][,helpfile,context])

In the MsgBox function syntax, the bold italic words are arguments of the function. Arguments enclosed in brackets are optional. (Do not type the brackets in your Visual Basic code.) For the MsgBox function, the only argument you must provide is the text for the prompt.

Arguments for functions and methods can be specified in code either by position or by name. To specify arguments by position, follow the order presented in the syntax. For example:

MsgBox "Your answer is correct!",0,"Answer Box"

To specify an argument by name, use the argument name followed by a colon and an equal sign and then the value. You can specify named arguments in any order. For example:

MsgBox Title:="Answer Box", Prompt:="Your answer is correct!"

The syntax for functions and some methods shows the arguments enclosed in parentheses. These functions and methods return values, so you must enclose the arguments in parentheses to assign the value to a variable. If you're ignoring the return value or if you're not passing arguments at all, do not include the parentheses. Methods that do not return values do not need their arguments enclosed in parentheses. These guidelines apply whether you're using positional arguments or named arguments.

In the following example, the return value from the MsgBox function (a number indicating which button was chosen) is stored in the variable myVar. Because the return value is used, parentheses are needed. Another message box then displays the value of the variable.

Sub Question()

myVar = MsgBox(Prompt:="I enjoy my job.", _

Title:="Answer Box", Buttons:="4")

MsgBox myVar

End Sub

Syntax for the Option Compare statement

Option Compare {Binary | Text}

In the Option Compare statement syntax, the curly brackets and straight line indicate a mandatory choice between two items. (Do not type the curly brackets in the Visual Basic statement). For example, the following statement specifies that within the module, strings will be compared in a case-insensitive sort order.

Option Compare Text

Syntax for the Dim statement

Dim varname[([subscripts])][As type][,varname[([subscripts])][As type]] . . .

In the Dim statement syntax, the word Dim is a required keyword. The only required element is varname (the variable name). For example, the following statement creates three variables: myVar, nextVar, and thirdVar. These variables are automatically declared as Variant data types.

Dim myVar, nextVar, thirdVar

The following example declares a variable as a string. Including a data type saves memory and can help you find errors in your code.

Dim myAnswer As String

If you want to declare several variables in one statement, you need to include the data type for each variable. Variables declared without a data type are automatically declared as Variant.

Dim x As Integer, y As Integer, z As Integer

In the following statement, x and y are assigned the variant type. Only z is assigned the Integer data type.

Dim x, y, z As Integer

If you are declaring an array variable, you must include the parentheses. You can include the subscripts, but that is also optional. The following statement dimensions a dynamic array, myArray.

Dim myArray()

For more information on arrays see Using arrays in Visual Basic.


LargeScroll Method

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.


SmallScroll Method

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.


CopyFromRecordset Method

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.


CopyFromRecordset Method 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


Cursor Property

Returns or sets the appearance of the mouse pointer in Microsoft Excel, as shown 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.


Cursor Property 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


EnableAutoFilter Property

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.

Remarks

This property applies to each worksheet and isn't saved with the worksheet or session.


EnableAutoFilter Property Example

This example enables the AutoFilter arrows on a protected worksheet.

ActiveSheet.EnableAutoFilter = True

ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


EnableOutlining Property

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.


EnableOutlining Property Example

This example enables outlining symbols on a protected worksheet.

ActiveSheet.EnableOutlining = True

ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


EnablePivotTable Property

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.


EnablePivotTable Property Example

This example enables PivotTable controls on a protected worksheet.

ActiveSheet.EnablePivotTable = True

ActiveSheet.Protect contents:=True, userInterfaceOnly:=True


PasswordEdit Property

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.


PasswordEdit Property Example

This example sets edit box one to display asterisks when the user enters data.

DialogSheets(1).EditBoxes(1).PasswordEdit = True


RefersToRange Property

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.


RefersToRange 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"


Item Method

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, select the accessor method or property from the following table.

AddIns Arcs AreaGroups Axes BarGroups Borders BuiltinDocumentProperties Buttons Cells Characters ChartGroups ChartObjects Charts CheckBoxes ChildItems ColumnFields ColumnGroups Columns CustomDocumentProperties DataFields DialogSheets Dialogs DoughnutGroups DrawingObjects Drawings	DropDowns EditBoxes Excel4IntlMacroSheets Excel4MacroSheets GroupBoxes GroupObjects HiddenFields HiddenItems Labels LegendEntries LineGroups Lines ListBoxes MenuBars MenuItems Menus Modules Names OLEObjects OptionButtons Ovals PageFields Panes ParentItems Pictures PieGroups PivotFields	PivotItems PivotTables Points RadarGroups Range Rectangles RowFields Rows Scenarios ScrollBars SeriesCollection Sheets ShortcutMenus Spinners Styles TextBoxes ToolbarButtons Toolbars Trendlines VisibleFields VisibleItems Windows Workbooks Worksheets XYGroups


DownBars Property

Accessor. Returns a DownBars object that represents the down bars on a line chart. Applies only to line charts. Read-only.


DropLines Property

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.


FirstSliceAngle Property

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.


HasDropLines Property

True if the line or area chart has drop lines. Applies only to line and area charts. Read-write.


HasHiLoLines Property

True if the line chart has high-low lines. Applies only to line charts. Read-write.


HasRadarAxisLabels Property

True if a radar chart has axis labels. Applies only to radar charts. Read-write.


HasSeriesLines Property

True if a stacked column or bar chart has series lines. Applies only to stacked column and bar charts. Read-write.


HasUpDownBars Property

True if a line chart has up and down bars. Applies only to line charts. Read-write.


HiLoLines Property

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.


Overlap Property

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.


RadarAxisLabels Property

Accessor. Returns a TickLabels object that represents the radar axis labels for the specified chart group. Read-only.


SeriesLines Property

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.


UpBars Property

Accessor. Returns an UpBars object that represents the up bars on a line chart. Applies only to line charts. Read-only.


VaryByCategories Property

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.


Add Method (Arcs and Lines)

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.


Add Method (Drawings Collection)

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.


Add Method (DropDowns Collection)

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.


AddVertex Method

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.


CentimetersToPoints Method

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.


ChartObjects Method

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.


CircularReference Property

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.


ColorButtons Property

True if toolbars are displayed using colored faces. Read-write.


ColorIndex Property

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.

The following illustration shows the color-index values in the default color palette.


DataLabels Method

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.


Explosion Property

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.


GetOpenFilename Method

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.


GetSaveAsFilename Method

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.


GridlineColorIndex Property

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.

The following illustration shows the color-index values in the default color palette.


InchesToPoints Method

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.


LinkCombo Method

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.


MarkerBackgroundColor Property

Returns or sets the marker background color as an RGB value. Line, scatter and radar charts only. Read-write.


MarkerBackgroundColorIndex Property

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.

Remarks

The following illustration shows the color-index values in the default color palette.


MarkerForegroundColor Property

Returns or sets the foreground color of the marker, specified as an RGB value. Line, scatter and radar charts only. Read-write.


MarkerForegroundColorIndex Property

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.

Remarks

The following illustration shows the color-index values in the default color palette.


OnRepeat Method

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.


OnSheetActivate Property

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.


OnSheetDeactivate Property

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.


OnUndo Method

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.


OutlineFont Property

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).


PatternColor Property

Returns or sets the interior pattern color as an RGB value. Read-write.


PatternColorIndex Property

Returns or sets the interior pattern color as an index into the current color palette. 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).

Remarks

The following illustration shows the color-index values in the default color palette.


ResetTipWizard Method

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.


ToolbarButtons Method

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.


Volatile Method

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.


AutoFormat Method

Chart object: Applies a built-in or custom autoformat to the specified chart.

Range object: Automatically formats a range of cells using a predefined format.


ActivateMicrosoftApp Method

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).


ActivateNext Method

Activates the specified window and then sends it to the back of the window z-order.

Syntax

object.ActivateNext

object

Required. The Window object.


ActivatePrevious Method

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.


AddIndent Property

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).


AxisTitle Property

Accessor. Returns an AxisTitle object that represents the title of the specified axis. Read-only.


CategoryNames Property

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.


ChartTitle Property

Accessor. Returns a ChartTitle object that represents the title of the specified chart. Read-only.


Deselect Method

Cancels the selection for the specified chart.

Syntax

object.Deselect

object

Required. The Chart object.


Display3DShading Property

True if the control uses 3-D visual effects. This property applies only to controls on worksheets and charts. Read-write.


DoughnutHoleSize Property

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.


EnableCancelKey Property

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.


EndStyle Property

Returns or sets the end style for the error bars (either xlCap or xlNoCap). Read-write.


MultiSelect Property

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.


 NavigateArrow Method

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.


OpenText Method

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))


RegisterXLL Method

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.


SaveCopyAs Method

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.


Selected Property

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.


UpdateFromFile Method

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.


WindowNumber Property

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.


XValues Property

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.


BCCRecipients Property

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".


CCRecipients Property

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".


Enclosures Property

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.


Mailer Property

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.


Received Property

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.


SendDateTime Property

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.


Sender Property

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.


SendMailer Method

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.


ToRecipients Property

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".


ExclusiveAccess Method

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.


ExclusiveAccess 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


MultiUserEditing Property

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.


MultiUserEditing 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 fileName:=ActiveWorkbook.FullName, _

accessMode:=xlShared

End If


ShowConflictHistory Property

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.


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


RevisionNumber Property

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.


RevisionNumber Property 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


UserStatus Property

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.


UserStatus Property 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


Changes to Visual Basic for Windows 95
Changes to Visual Basic in Microsoft Excel for Windows 95

Top

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. For more information about these changes and additions, select one of the items in the following list, or scroll through this topic to find the information.

Changed Properties and Methods

AutoCorrect Support

OLE Document Properties Support

AutoComplete Support

Protection Control

Appearance Control

Miscellaneous

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.


AddIn Object

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.


AddIns Collection Object

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


Application Object

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.


AddIn, Debug, Dialog, MenuBar, Toolbar, Window, Workbook


Arc Object

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)


A Chart sheet, DialogSheet, or Worksheet.


Arcs Collection Object

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


Areas Collection Object

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


Border, Characters, Font, Interior, Name, SoundNote, Style


Axes Collection Object

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


Axis Object

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


AxisTitle Object

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.


Border, Characters, Font, Interior


Border Object

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.


Arc, Arcs, Axis, AxisTitle, ChartArea, ChartObject, ChartObjects, ChartTitle, CheckBox, CheckBoxes, DataLabel, DataLabels, DownBars, Drawing, DrawingObjects, Drawings, DropLines, ErrorBars, Floor, Gridlines, GroupObject, GroupObjects, HiLoLines, Legend, LegendKey, Line, Lines, OLEObject, OLEObjects, OptionButton, OptionButtons, Oval, Ovals, Picture, Pictures, PlotArea, Point, Rectangle, Rectangles, Series, SeriesLines, TextBox, TextBoxes, Trendline, UpBars, Walls


Borders Collection Object

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.


Range, Style


Button Object

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


Buttons Collection Object

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.


Characters Object

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


AxisTitle, Button, Buttons, ChartTitle, CheckBox, CheckBoxes, DataLabel, DialogFrame, DrawingObjects, DropDown, DropDowns, EditBox, EditBoxes, GroupBox, GroupBoxes, Label, Labels, OptionButton, OptionButtons, Range, TextBox, TextBoxes


Chart Object

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


Arc, Axis, Button, ChartArea, ChartGroup, ChartObject, ChartTitle, CheckBox, Corners, Drawing, DrawingObjects, DropDown, Floor, GroupBox, GroupObject, Label, Legend, Line, ListBox, OLEObject, OptionButton, Oval, PageSetup, Picture, PlotArea, Rectangle, ScrollBar, Series, Spinner, TextBox, Walls


ChartArea Object

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


DialogSheet or Worksheet


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 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


ChartGroups Collection Object

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


ChartObject Object

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


ChartObjects Collection Object

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


Charts Collection Object

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.


ChartTitle Object

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.


CheckBox Object

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


CheckBoxes Collection Object

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


Corners Object

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.


DataLabel Object

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


DataLabels Collection Object

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


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.

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."


DialogFrame Object

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.


Dialogs Collection Object

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


DialogSheet Object

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.


Arc, Button, ChartObject, CheckBox, DialogFrame, Drawing, DrawingObjects, DropDown, EditBox, GroupBox, GroupObject, Label, Line, ListBox, OLEObject, OptionButton, Oval, PageSetup, Picture, Rectangle, ScrollBar, Spinner, TextBox


DialogSheets Collection Object

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.


DownBars Object

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.


Drawing Object

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


Graphic Objects

Objects drawn with buttons on the Drawing toolbar:

Arc, Button, Drawing, Line, Oval, Rectangle, TextBox


Controls

Objects drawn with buttons on the Forms toolbar:

Button, CheckBox, DropDown, EditBox, GroupBox, GroupObject, Label, ListBox, OptionButton, ScrollBar, Spinner


DrawingObjects Collection Object

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.


Border, Characters, Font, Interior


Drawings Collection Object

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.


DropDown Object

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

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"


DropDowns Collection Object

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


DropLines Object

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.


EditBox Object

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


EditBoxes Collection Object

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 = ""


ErrorBars Object

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.


Floor Object

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)


Font Object

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.


AxisTitle, Button, Buttons, Characters, ChartArea, ChartTitle, DataLabel, DataLabels, DrawingObjects, GroupObject, GroupObjects, Legend, LegendEntry, Range, Style, TextBox, TextBoxes, TickLabels


Gridlines Object

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


GroupBox Object

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


GroupBoxes Collection Object

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


GroupObject Object

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


GroupObjects Collection Object

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


HiLoLines Object

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.


Interior Object

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


Arc, Arcs, AxisTitle, ChartArea, ChartObject, ChartObjects, ChartTitle, CheckBox, CheckBoxes, DataLabel, DataLabels, DownBars, Drawing, DrawingObjects, Drawings, Floor, GroupObject, GroupObjects, Legend, LegendKey, OLEObject, OLEObjects, OptionButton, OptionButtons, Oval, Ovals, Picture, Pictures, PlotArea, Point, Range, Rectangle, Rectangles, Series, Style, TextBox, TextBoxes, UpBars, Walls


Label Object

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


Labels Collection Object

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


Legend Object

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.


LegendEntries Collection Object

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


LegendEntry Object

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.


LegendKey Object

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


Line Object

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


Lines Collection Object

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


ListBox Object

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.


ListBoxes Collection Object

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


Mailer Object

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."


Menu Object

Represents a drop-down menu, shortcut menu, or submenu. For more information on the menu structure, see Menu Structure.

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).


MenuBar Object

Represents a built-in or custom menu bar. For more information on the menu structure, see Menu Structure.

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


MenuBars Collection Object

A collection of all the MenuBar objects in the Microsoft Excel application. Each MenuBar object represents a built-in or custom menu bar. For more information on the menu structure, see Menu Structure.

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.


MenuItem Object

Represents an item on a menu (either a command or a separator bar). For more information on the menu structure, see Menu Structure.

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


MenuItems Collection Object

A collection of all the MenuItem objects on the specified menu. For more information on the menu structure, see Menu Structure.

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


Menus Collection Object

A collection of all the Menu objects on the specified menu bar. Each Menu object represents a drop-down menu, shortcut menu, or submenu. For more information on the menu structure, see Menu Structure.

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.


Module Object

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


Modules Collection Object

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.


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.

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


Names Collection Object

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"


OLEObject Object

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


OLEObjects Collection Object

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"


OptionButton Object

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


OptionButtons Collection Object

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

op_btns.Ungroup


Outline Object

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


Oval Object

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)


Ovals Collection Object

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


PageSetup Object

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


Chart, DialogSheet, Module, Window, Worksheet


Pane Object

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


Panes Collection Object

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


Picture Object

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


Pictures Collection Object

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.


PivotField Object

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 pivot table, 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 pivot table fields. The following accessor methods are available:

ColumnFields method

DataFields method

HiddenFields method

PageFields method

RowFields method

VisibleFields method


PivotFields Collection Object

A collection of all the PivotField objects in a pivot table.

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 table fields. The following accessor methods are available:

ColumnFields method

DataFields method

HiddenFields method

PageFields method

RowFields method

VisibleFields method


PivotItem Object

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


PivotItems Collection Object

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


PivotTable Object

Represents a pivot table 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 pivot table and add it to the collection.

To access a single member of the collection, use the PivotTables method with the pivot table index number or name as an argument.

The following example makes the field named "year" a row field in pivot table one on the worksheet named "Sheet3."

Worksheets("sheet3").PivotTables(1) _

    .PivotFields("year").Orientation = xlRowField

Use the Name property to set or return the pivot table name. The following example moves the field named "year" on the pivot table named "PivotTable2."

Worksheets("sheet3").PivotTables("pivottable2") _

    .PivotFields("year").Position = 2

Because pivot table programming can be complex, it is generally easier to record pivot table actions by clicking the Record Macro command on the Tools menu.


PivotTables Collection Object

A collection of all the PivotTable objects on the specified worksheet.

Accessors

Use the PivotTableWizard method to create a new pivot table 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 pivot tables on the worksheet named "Sheet3."

MsgBox Worksheets("sheet3").PivotTables.Count


PlotArea Object

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


Point Object

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


Points Collection Object

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


Range Object

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


Areas, Border, Characters, Font, Interior, Name, SoundNote, Style


Rectangle Object

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


Rectangles Collection Object

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


RoutingSlip Object

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.


Scenario Object

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


Scenarios Collection Object

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")


ScrollBar Object

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"


ScrollBars Collection Object

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.

Worksheets("sheet1").ScrollBars.Value = 0


Series Object

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


SeriesCollection Collection Object

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")


SeriesLines Object

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.


Sheets Collection Object

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)


Chart, DialogSheet, Module, or Worksheet


SoundNote Object

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


Spinner Object

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


Spinners Collection Object

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


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). 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.


Range, Workbook


Styles Collection Object

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.


TextBox Object

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


TextBoxes Collection Object

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


TickLabels Object

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"


Toolbar Object

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


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

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.

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).


ToolbarButtons Collection Object

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.

To add a gap instead of a button, omit the button argument for the Add method.


Toolbars Collection Object

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."


Trendline Object

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


Trendlines Collection Object

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.


UpBars Object

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.


Walls Object

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


Window Object

(Info Window only)

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


Windows Collection Object

(Info Window only)

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


Workbook Object

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.


Chart, Dialogsheet, Mailer, Module, Name, PageSetup, RoutingSlip, Style, Window, Worksheet


Workbooks Collection Object

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


Worksheet Object

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


Arc, Button, ChartObject, CheckBox, Drawing, DrawingObjects, DropDown, GroupBox, GroupObject, Label, Line, ListBox, OLEObject, OptionButton, Outline, Oval, PageSetup, Picture, PivotTable, Range, Rectangle, Scenario, ScrollBar, Spinner, TextBox


Worksheets Collection Object

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.


ForwardMailer Method

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.


HasMailer Property

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.


HasRoutingSlip Property

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.


Reply Method

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.


ReplyAll Method

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.


Route Method

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.


Routed Property

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).


RoutingSlip Property

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.


SendMail Method

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.

Use the SendMailer method on PowerTalk email systems on the Apple Macintosh. The Mailer object contains the addressing information for PowerTalk.


DocumentProperty Object (Microsoft Excel)

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"

To use this object, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).


DocumentProperties Collection Object (Microsoft Excel)

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.

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

To use this object, you should establish a reference to the Microsoft Office 95 Object Library by using the References command (Tools menu).


LinkSource Property (Microsoft Excel)

For Microsoft Excel, the source is a name in the workbook.


Add Method (Microsoft Excel)

For Microsoft Excel, the linkSource argument specifies a name in the workbook.


BuiltinDocumentProperties Property

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.


BuiltinDocumentProperties Property 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


CustomDocumentProperties Property

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("Complete")

CustomDocumentProperties("Complete")

Use the BuiltinDocumentProperties property to return the collection of built-in document properties.


CustomDocumentProperties Property 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


Add Method Example (Microsoft Excel)

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


Count Property Example (Microsoft Excel)

This example displays the number of custom document properties in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties.Count


Delete Method Example (Microsoft Excel)

This example deletes the "Total Sales" custom document property

ActiveWorkbook.CustomDocumentProperties("Total Sales").Delete


Item Method Example (Microsoft Excel)

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


LinkToContent Property Example (Microsoft Excel)

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


LinkSource Property Example (Microsoft Excel)

This example links the custom document property named "TotalSales" to the named range "SalesNumbers" in the active workbook.

ActiveWorkbook.CustomDocumentProperties _

.Item("TotalSales").LinkSource = "SalesNumbers"


Name Property Example (Microsoft Excel)

This example displays the name of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Name


Type Property Example (Microsoft Excel)

This example displays the type of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Type


Value Property Example (Microsoft Excel)

This example displays the value of custom document property one in the active workbook.

MsgBox ActiveWorkbook.CustomDocumentProperties(1).Value


AutomaticStyles Property

True if the outline uses automatic styles. Read-write.


ShowLevels Method

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.


SummaryColumn Property

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.


SummaryRow Property

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.


BottomMargin Property

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.


CenterFooter Property

Returns or sets the center part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.


CenterHeader Property

Returns or sets the center part of the header. Read-write.

Remarks

Special format codes can be used in the header text.


CenterHorizontally Property

True if the sheet is centered horizontally on the page. Read-write.


CenterVertically Property

True if the sheet is centered vertically on the page. Read-write.


ChartSize Property

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).


FirstPageNumber Property

Returns or sets the first page number that will be used for printing this sheet (the default value is xlAutomatic). Read-write.


FitToPagesTall Property

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.


FitToPagesWide Property

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.


LeftFooter Property

Returns or sets the left part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.


LeftHeader Property

Returns or sets the left part of the header. Read-write.

Remarks

Special format codes can be used in the header text.


LeftMargin Property

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.


Order Property

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.


PaperSize Property

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.


PrintGridlines Property

True if cell gridlines are printed on the page. Read-write.

Remarks

This property applies only to worksheets.


PrintHeadings Property

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.


RightFooter Property

Returns or sets the right part of the footer. Read-write.

Remarks

Special format codes can be used in the footer text.


 RightHeader Property

Returns or sets the right part of the header. Read-write.

Remarks

Special format codes can be used in the header text.


RightMargin Property

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.


TopMargin Property

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.


Zoom Property

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.


Formatting Codes for Headers and Footers

The following special formatting codes can be included as a part of the header and footer properties (LeftHeader, CenterHeader, RightHeader, LeftFooter, CenterFooter, RightFooter).

Format Code	Description

&L	Left-aligns the characters that follow

&C	Centers the characters that follow

&R	Right-aligns the characters that follow

&E	Turns double-underline printing on or off

&X	Turns superscript printing on or off

&Y	Turns subscript printing on or off

&B	Turns bold printing on or off.

&I	Turns italic printing on or off.

&U	Turns underline 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.

&F	Prints the name of the document.

&A	Prints the name of the workbook tab

&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"	Prints the characters that follow in the specified font. Be sure to include the double quotation marks.

&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 document.


AddCustomList Method

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.


AlertBeforeOverwriting Property

True if Microsoft Excel displays a message before overwriting non-blank cells during a drag and drop editing operation. Read-write.


ClipboardFormats Property

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


DeleteCustomList Method

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.


EnableTipWizard Property

True if the TipWizard is enabled. Read-write.


FileConverters Property

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.


GetCustomListContents Method

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.


GetCustomListNum Method

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.


EditDirectlyInCell Property

True if Microsoft Excel allows editing in cells. Read-write.


MailLogoff Method

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.


MailLogon Method

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.


MailSession Property

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.


MailSystem Property

Returns the mail system installed on the host machine (one of xlNoMailSystem, xlMAPI, or xlPowerTalk). Read-only.


NextLetter Method

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.


OnCalculate Property

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.


PromptForSummaryInfo Property

True if Microsoft Excel asks for summary info when files are initially saved. Read-write.


SheetsInNewWorkbook Property

Returns or sets the number of sheets Microsoft Excel automatically inserts in new workbooks. Read-write.


StandardFont Property

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.


StandardFontSize Property

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.


AutoFilter Method

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.


DisplayHorizontalScrollBar Property

True if the horizontal scroll bar is displayed. Read-write.


DisplayVerticalScrollBar Property

True if the vertical scroll bar is displayed. Read-write.


DisplayWorkbookTabs Property

True if the workbook tabs are displayed. Read-write.


Draft Property

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).


FilterMode Property

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.


FontStyle Property

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).


FooterMargin Property

Returns or sets the distance from the bottom of the page to the footer, in points (1/72 inch). Read-write.


HeaderMargin Property

Returns or sets the distance from the top of the page to the header, in points (1/72 inch). Read-write.


PrintNotes Property

True if cell notes will be printed along with the sheet. Read-write.

Remarks

This property applies only to worksheet pages.


PrintQuality Property

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.


ScrollColumn Property

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.


ScrollRow Property

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.


ScrollWorkbookTabs Method

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.


Shadow Property

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).


Subscript Property

True if the font is subscripted. Read-write.

Remarks

This property is False by default.


Superscript Property

True if the font is superscripted. Read-write.

Remarks

This property is False by default.


TabRatio Property

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).


Charts Method

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.


ClearArrows Method

Clears the tracer arrows on the worksheet. Tracer arrows are added by the auditing feature.

Syntax

object.ClearArrows

object

Required. The Worksheet object.


Copy Method

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.


DrawingObjects Method

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.


GroupObjects Method

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).


Move Method

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.


OnDoubleClick Property

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.


PrintOut Method

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.


PrintPreview Method

Shows a preview of the object as it would be printed.

Syntax

object.PrintPreview

object

Required. The object to preview.


Protect Method

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.


ProtectContents Property

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.


ProtectDrawingObjects Property

True if the drawing objects of a sheet are protected. On a dialog sheet, this protects the layout of the controls. Read-only.


Scenarios Method

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).


Unprotect Method

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.


AskToUpdateLinks Property

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.


AutoUpdate Property

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.


Backward Property

Returns or sets the number of periods (or units on a scatter chart) that the trendline extends backward. Read-write.


BlackAndWhite Property

True if elements of the document will be printed in black and white. Read-write.

Remarks

This property applies only to worksheet pages.


Category Property

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.


ChangeFileAccess Method

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.


ChartGroups Method

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.


Checked Property

True if the menu item is checked. Read-write.


CopyObjectsWithCells Property

True if drawing objects are cut, copied, extracted, and sorted with cells. Read-write.


Count Property

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.


CustomListCount Property

Returns the number of defined custom lists (including built-in lists). Read-only.


DefaultFilePath Property

Returns or sets the default path Microsoft Excel uses when it opens files. Read-write.


Dialogs Method

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.

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.


DisplayBlanksAs Property

Returns or sets how blank cells are plotted on a chart (one of xlNotPlotted, xlInterpolated, or xlZero). Read-write.


DisplayEquation Property

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.


DisplayFullScreen Property

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.


DisplayExcel4Menus Property

True if Microsoft Excel displays version 4.0 menu bars. Read-write.


DisplayRecentFiles Property

True if the most recently used (MRU) file list is displayed on the File menu. Read-write.


DisplayRSquared Property

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.


Duplicate Method

Duplicates the object and returns a reference to the new copy.

Syntax

object.Duplicate

object

Required. The object to which this method applies.


Edit Method

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).


FindFile Method

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.


Forward Property

Returns or sets the number of periods (or units on a scatter chart) that the trendline extends forward. Read-write.


HasTitle Property

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.


InsertFile Method

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.


Intercept Property

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.

Remarks

Setting this property causes the InterceptIsAuto property to be set to False.


InterceptIsAuto Property

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.


LargeButtons Property

True if Microsoft Excel is using large toolbar buttons. False if Microsoft Excel is using standard toolbar buttons. Read-write.


MacroType Property

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.


MenuItems Method

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


Menus Method

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).


NameIsAuto Property

True if Microsoft Excel automatically determines the name of the trendline. Read-write.


Object Property

Returns the OLE Automation object associated with this OLE object. Read-only.


OLEObjects Method

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.


OLEType Property

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.


Pattern Property

Returns or sets the pattern of the interior. Read-write.

Remarks

This property can have one of the following values.


Period Property

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.


PlotVisibleOnly Property

True if only visible cells are plotted (False if both visible and hidden cells are plotted). Read-write.


PrintArea Property

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.


PrintTitleColumns Property

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.


PrintTitleRows Property

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.


VisibleRange Property

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.


RefersTo Property

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.


ShowDetail Property

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.


TransitionMenuKeyAction Property

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.


Update Method

Updates the link.

Syntax

object.Update

object

Required. The OLEObject object.


Verb Method

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).


WallsAndGridlines2D Property

True if gridlines are drawn in 2-D on a 3-D chart. Read-write.


AddMenu Method

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.


AdvancedFilter Method

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.


Caller Property

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
This property returns information about how Visual Basic was called, not how the current procedure was called. For example, if the user clicks button 4, which calls Macro1, and Macro1 calls Macro2, and Macro2 uses the Caller property, the property will return "Button 4".


CheckSpelling Method

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.


Colors Property

Returns or sets an array of colors (from 1 to 56) in the palette for the workbook. Read-write.


DisplayRightToLeft Property

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.


FillAcrossSheets Method

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.


Name Property

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 .


NameLocal Property

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.


Range Method

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.


RecordMacro Method

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.


Show Method

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. To find the arguments to set, search Built-In Dialog Box Argument Lists for the corresponding dialog box constant. For example, search for the xlDialogOpen constant to find the arguments for the Open dialog box. For more information about built-in dialog boxes, see Dialogs.


ShowAllData Method

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.


Value Property

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.

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.


Accelerator Property

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.


ActiveChart Property

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.


ActiveDialog Property

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.


AddChartAutoFormat Method

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.


AddFields Method

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.


AddItem Method

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.


AutoFilterMode Property

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.


AutoOutline Method

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.


BorderAround Method

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.


CancelButton Property

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.


ChangeLink Method

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.


ChartWizard Method

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.


CheckBoxes Method

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 1

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).


ClearOutline Method

Clears the outline for the specified range.

Syntax

object.ClearOutline

object

Required. The Range object.


ConsolidationFunction Property

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.


ConsolidationOptions Property

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.


ConsolidationSources Property

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.


DefaultButton Property

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.


DeleteChartAutoFormat Method

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.


DialogFrame Property

Accessor. Returns a DialogFrame object that represents the dialog frame on the specified dialog sheet. Read only.


DismissButton Property

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.


DisplayClipboardWindow Property

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.


DisplayInfoWindow Property

True if the Info window is displayed. Set this property to True to display the Info window. Read-write.


DropDownLines Property

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.


DropDowns Method

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).


EditBoxes Method

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 more than one).


EditionOptions Method

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.


Extend Method

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.


Focus Property

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.


GroupBoxes Method

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).


HelpButton Property

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.


Hide Method

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.


InnerDetail Property

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.


InputType Property

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.


Labels Method

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).


LargeChange Property

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.


LegendEntries Method

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.


LegendKey Property

Accessor. Returns a LegendKey object that represents the legend key associated with the entry.


LinkedCell Property

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.


LinkedObject Property

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.


LinkInfo Method

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.


LinkSources Method

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.


List Property

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.


ListBoxes Method

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).


ListCount Property

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.


ListFillRange Property

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 ("").


ListIndex Property

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.


Max Property

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.

Remarks

The value of the Max property must be greater than the value of the Min property.


Merge Method

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.


Min Property

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.

Remarks

The value of the Min property must be less than the value of the Max property.


MultiLine Property

True if the edit box is multi-line enabled. Read-write.


OpenLinks Method

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.


OptionButtons Method

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).


ProtectScenarios Property

True if the worksheet scenarios are protected. Read-only.


RemoveAllItems Method

Removes all entries from a list box or drop-down list box.

Syntax

object.RemoveAllItems

object

Required. The object to which this method applies.


RemoveItem Method

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.


ScrollBars Method

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).


SetInfoDisplay Method

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.


SetLinkOnData Method

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.


ShortcutKey Property

Returns or sets the shortcut key for a name defined as a custom Microsoft Excel version 4.0 macro command. Read-write.


ShowToolTips Property

True if ToolTips are turned on. Read-write.


SizeWithWindow Property

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.


SmallChange Property

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.


Spinners Method

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).


TextToColumns Method

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))


UpdateLink Method

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.


Paste Method

Object	Description

Chart 	Pastes chart data from the Clipboard into the specified Chart.

Pictures	Pastes a picture from the Clipboard to a sheet or chart. The position of the new picture is determined by the current selection.

Point or Series	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.

SeriesCollection	Pastes data from the Clipboard to the specified series collection.

DialogSheet or Worksheet	Pastes the contents of the Clipboard onto the sheet.


Paste Method (Chart Object)

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.


Paste Method (Pictures Object)

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.


Paste Method (Point or Series Object)

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.


Paste Method (SeriesCollection Object)

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.


Paste Method (DialogSheet or Worksheet Object)

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.


PasteSpecial Method

Range:	Pastes a Range from the Clipboard to the specified range.

DialogSheet or Worksheet: 	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.


PasteSpecial Method (Range Object)

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.


PasteSpecial Method (DialogSheet or Worksheet Object)

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.


ApplyDataLabels Method

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.


DataLabel Property

Accessor. Returns a DataLabel object that represents the data label associated with the point or trendline. Read-only.


HasDataLabel Property

True if the point has a data label. Read-write.


MarkerStyle Property

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.


PictureType Property

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.


PictureUnit Property

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.


BaseField Property

Returns or sets the base field for the custom calculation. Valid only for data fields. Read-write.


BaseItem Property

Returns or sets the item in the base field for the custom calculation. Valid only for data fields. Read-write.


Calculation Property

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.


ChildField Property

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.


ChildItems Method

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).


CurrentPage Property

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.


DataRange Property

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


DataType Property

Returns a constant describing the type of data in the pivot field. Can be xlText, xlNumber, or xlDate. Read-only.


Group Method

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.


GroupLevel Property

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.


HiddenItems Method

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).


LabelRange Property

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.


Orientation Property

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.


ParentField Property

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.


ParentItems Method

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).


PivotItems Method

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).


Position Property

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.


Subtotals Property

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

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.


TotalLevels Property

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.


Ungroup Method

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.


VisibleItems Method

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).


ParentItem Property

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.


ParentShowDetail Property

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.


SourceName Property

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.


LocationInTable Property

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.


PivotField Property

Accessor. Returns a PivotField object that represents the pivot field containing the top left corner of the specified range. Read-only.


PivotItem Property

Accessor. Returns a PivotItem object that represents the pivot item containing the top left corner of the specified range. Read-only.


PivotTable Property

Accessor. Returns a PivotTable object that represents the PivotTable containing the top left corner of the specified range. Read-only.


ColumnFields Method

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).


ColumnGrand Property

True if the PivotTable shows column grand totals. Read-write.


ColumnRange Property

Accessor. Returns a Range object that represents the range that contains the PivotTable column area. Read-only.


DataBodyRange Property

Accessor. Returns a Range object that represents the range that contains the PivotTable data area. Read-only.


DataFields Method

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).


DataLabelRange Property

Accessor. Returns a Range object that represents the range that contains the PivotTable data field labels. Read-only.


HasAutoFormat Property

True if the PivotTable is automatically formatted when it is refreshed or when fields are moved. Read-write.


HiddenFields Method

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).


PageFields Method

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).


PageRange Property

Accessor. Returns a Range object that represents the range that contains the PivotTable page area. Read-only.


PivotFields Method

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).


RefreshDate Property

Returns the date when the PivotTable was last refreshed. Read-only.


RefreshName Property

Returns the name of the person who last refreshed the PivotTable data. Read-only.


RefreshTable Method

Refreshes the PivotTable from the source data. Returns True if it is successful.

Syntax

object.RefreshTable

object

Required. The PivotTable object.


RowFields Method

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).


RowGrand Property

True if the pivot table shows row grand totals. Read-write.


RowRange Property

Accessor. Returns a Range object that represents the range that includes the PivotTable row area. Read-only.


SaveData Property

True if data for the PivotTable is saved with the workbook; False if only the PivotTable definition is saved. Read-write.


ShowPages Method

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.


TableRange1 Property

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.


TableRange2 Property

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.


VisibleFields Method

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).


PivotTables Method

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).


PivotTableWizard Method

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.


Address Method

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.


ApplyNames Method

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.


ApplyOutlineStyles Method

Applies outlining styles to the range.

Syntax

object.ApplyOutlineStyles

object

Required. The range where outlining styles will be applied.


Areas Method

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.


AutoFill Method

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.


AutoFormat Method (Range object)

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.


AutoFit Method

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.


ClearNotes Method

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.


Column Property

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


ColumnDifferences Method

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.


ColumnWidth Property

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.


Consolidate Method

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.


CreateNames Method

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.


CurrentArray Property

Accessor. If the specified cell is part of an array, returns a Range object that represents the entire array. Read-only.


CurrentRegion Property

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.


DataSeries Method

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.


Dependents Property

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.


DialogBox Method

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.


DirectDependents Property

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.


DirectPrecedents Property

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.


End Method

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.


EntireColumn Property

Accessor. Returns a Range object that represents the entire column (or columns) that contain the specified range. Read-only.


EntireRow Property

Accessor. Returns a Range object that represents the entire row (or rows) that contain the specified range. Read-only.


FillDown Method

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.


FillLeft Method

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.


FillRight Method

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.


FillUp Method

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.


Find Method

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.

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


FindNext Method

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.


FindPrevious Method

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.


FormulaArray Property

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.


FormulaHidden Property

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.


GoalSeek Method

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.


Goto Method

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.


HasArray Property

True if the specified cell is a part of an array. Read-only.


HasFormula Property

True if all cells in the range contain formulas; False if no cell in the range contains a formula; Null otherwise. Read-only.


Hidden Property

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.


Justify Method

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.


ListNames Method

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.


Next Property

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.


NoteText Method

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.


NumberFormatLocal Property

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.


Offset Method

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.


OutlineLevel Property

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.


PageBreak Property

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.


Parse Method

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.


Precedents Property

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.


PrefixCharacter Property

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.


Previous Property

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.


Replace Method

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.

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.


Resize Method

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.


Row Property

Returns the number of the first row of the first area of the range. Read-only.


RowDifferences Method

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.


RowHeight Property

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.


Select Method

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.


SoundNote Property

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.


Style Property

Accessor. Returns a Style object that represents the style of the specified range. Read-only.


SubscribeTo Method

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.


Summary Property

True if the range is an outlining summary row or column. The range should be a row or a column. Read-only.


Table Method

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.


UseStandardHeight Property

True if the row height of the Range object equals the standard height of the sheet. Read-write.


UseStandardWidth Property

True if the column width of the Range object equals the standard width of the sheet. Read-write.


VerticalAlignment Property

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.


Worksheet Property

Accessor. Returns a Worksheet object that represents the worksheet containing the specified range. Read-only.


WrapText Property

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.


Borders Method

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).


CopyPicture Method

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.


Cut Method

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.


Formula Property

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.


FunctionWizard Method

Starts the Function Wizard for the upper left cell of the range.

Syntax

object.FunctionWizard

object

Required. The Range object.


HorizontalAlignment Property

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.


Interior Property

Accessor. Returns an Interior object that represents the interior of the specified object. Read-only.


Locked Property

False if the object can be modified when the sheet is protected. Read-write.


NumberFormat Property

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.


RemoveSubtotal Method

Removes subtotals from a list.

Syntax

object.RemoveSubtotal

object

Required. The Range object.


ShowDependents Method

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.


ShowErrors Method

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.


ShowPrecedents Method

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.


Sort Method

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).


Subtotal Method

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.

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.


Delivery Property

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.


Message Property

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.


Recipients Property

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.


Reset Method

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).


ReturnWhenDone Property

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.


Status Property

Indicates the status of the routing slip (one of xlNotYetRouted, xlRoutingInProgress, or xlRoutingComplete). Read-only.


TrackStatus Property

True if status tracking is enabled for the routing slip. Read-write before routing begins; read-only when routing is in progress.


ChangeScenario Method

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.


ChangingCells Property

Accessor. Returns a Range object that represents the changing cells for a scenario. Read only.


Comment Property

Returns or sets the comment associated with the scenario. The comment text cannot exceed 255 characters. Read-write.


CreateSummary Method

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.


ErrorBar Method

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.


ErrorBars Property

Accessor. Returns an ErrorBars object that represents the error bars for the series. Read-only.


HasErrorBars Property

True if the series has error bars. This property is not available on 3-D charts. Read-write.


InvertIfNegative Property

True if Microsoft Excel inverts the pattern in the item when it corresponds to a negative number. Read-write.


PlotOrder Property

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.


Points Method

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.


Smooth Property

True if the line or scatter chart has curve smoothing on. Applies only to line and scatter charts. Read-write.


Trendlines Method

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.


Values Property

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.


Built-In Dialog Box Argument Lists

Dialog Constant	Argument List(s)
xlDialogActivate	window_text, pane_num
xlDialogActiveCellFont	font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count
xlDialogAddChartAutoformat	name_text, desc_text
xlDialogAddinManager	operation_num, addinname_text, copy_logical
xlDialogAlignment	horiz_align, wrap, vert_align, orientation, add_indent
xlDialogApplyNames	name_array, ignore, use_rowcol, omit_col, omit_row, order_num, append_last
xlDialogApplyStyle	style_text
xlDialogAppMove	x_num, y_num
xlDialogAppSize	x_num, y_num
xlDialogArrangeAll	arrange_num, active_doc, sync_horiz, sync_vert
xlDialogAssignToObject	macro_ref
xlDialogAssignToTool	bar_id, position, macro_ref
xlDialogAttachText	attach_to_num, series_num, point_num
xlDialogAttachToolbars
xlDialogAutoCorrect	correct_initial_caps, capitalize_days
xlDialogAxes	x_primary, y_primary, x_secondary, y_secondary
xlDialogAxes	x_primary, y_primary, z_primary
xlDialogBorder	outline, left, right, top, bottom, shade, outline_color, left_color, right_color, top_color, bottom_color
xlDialogCalculation	type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values, alt_exp, alt_form
xlDialogCellProtection	locked, hidden
xlDialogChangeLink	old_text, new_text, type_of_link
xlDialogChartAddData	ref, rowcol, titles, categories, replace, series
xlDialogChartTrend	type, ord_per, forecast, backcast, intercept, equation, r_squared, name
xlDialogChartWizard	long, ref, gallery_num, type_num, plot_by, categories, ser_titles, legend, title, x_title, y_title, z_title, number_cats, number_titles
xlDialogCheckboxProperties	value, link, accel_text, accel2_text, 3d_shading
xlDialogClear	type_num
xlDialogColorPalette	file_text
xlDialogColumnWidth	width_num, reference, standard, type_num, standard_num
xlDialogCombination	type_num
xlDialogConsolidate	source_refs, function_num, top_row, left_col, create_links
xlDialogCopyChart	size_num
xlDialogCopyPicture	appearance_num, size_num, type_num
xlDialogCreateNames	top, left, bottom, right
xlDialogCreatePublisher	file_text, appearance, size, formats
xlDialogCustomizeToolbar	category
xlDialogDataDelete
xlDialogDataLabel	show_option, auto_text, show_key
xlDialogDataSeries	rowcol, type_num, date_num, step_value, stop_value, trend
xlDialogDefineName	name_text, refers_to, macro_type, shortcut_text, hidden, category, local
xlDialogDefineStyle	style_text, number, font, alignment, border, pattern, protection
xlDialogDefineStyle	style_text, attribute_num, additional_def_args, ...
xlDialogDeleteFormat	format_text
xlDialogDeleteName	name_text
xlDialogDemote	row_col
xlDialogDisplay	formulas, gridlines, headings, zeros, color_num, reserved, outline, page_breaks, object_num
xlDialogDisplay	cell, formula, value, format, protection, names, precedents, dependents, note
xlDialogEditboxProperties	validation_num, multiline_logical, vscroll_logical, password_logical
xlDialogEditColor	color_num, red_value, green_value, blue_value
xlDialogEditDelete	shift_num
xlDialogEditionOptions	edition_type, edition_name, reference, option, appearance, size, formats
xlDialogEditSeries	series_num, name_ref, x_ref, y_ref, z_ref, plot_order
xlDialogErrorbarX	include, type, amount, minus
xlDialogErrorbarY	include, type, amount, minus
xlDialogExtract	unique
xlDialogFileDelete	file_text
xlDialogFillGroup	type_num
xlDialogFillWorkgroup	type_num
xlDialogFilterAdvanced	operation, list_ref, criteria_ref, copy_ref, unique
xlDialogFindFile
xlDialogFont	name_text, size_num
xlDialogFontProperties	font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count
xlDialogFormatAuto	format_num, number, font, alignment, border, pattern, width
xlDialogFormatChart	layer_num, view, overlap, angle, gap_width, gap_depth, chart_depth, doughnut_size, axis_num, drop, hilo, up_down, series_line, labels, vary
xlDialogFormatCharttype	apply_to, group_num, dimension, type_num
xlDialogFormatFont	color, backgd, apply, name_text, size_num, bold, italic, underline, strike, outline, shadow, object_id, start_num, char_num
xlDialogFormatFont	name_text, size_num, bold, italic, underline, strike, color, outline, shadow
xlDialogFormatFont	name_text, size_num, bold, italic, underline, strike, color, outline, shadow, object_id_text, start_num, char_num
xlDialogFormatLegend	position_num
xlDialogFormatMain	type_num, view, overlap, gap_width, vary, drop, hilo, angle, gap_depth, chart_depth, up_down, series_line, labels, doughnut_size
xlDialogFormatMove	x_offset, y_offset, reference
xlDialogFormatMove	x_pos, y_pos
xlDialogFormatMove	explosion_num
xlDialogFormatNumber	format_text
xlDialogFormatOverlay	type_num, view, overlap, gap_width, vary, drop, hilo, angle, series_dist, series_num, up_down, series_line, labels, doughnut_size
xlDialogFormatSize	width, height
xlDialogFormatSize	x_off, y_off, reference
xlDialogFormatText	x_align, y_align, orient_num, auto_text, auto_size, show_key, show_value, add_indent
xlDialogFormulaFind	text, in_num, at_num, by_num, dir_num, match_case, match_byte
xlDialogFormulaGoto	reference, corner
xlDialogFormulaReplace	find_text, replace_text, look_at, look_by, active_cell, match_case, match_byte
xlDialogFunctionWizard
xlDialogGallery3dArea	type_num
xlDialogGallery3dBar	type_num
xlDialogGallery3dColumn	type_num
xlDialogGallery3dLine	type_num
xlDialogGallery3dPie	type_num
xlDialogGallery3dSurface	type_num
xlDialogGalleryArea	type_num, delete_overlay
xlDialogGalleryBar	type_num, delete_overlay
xlDialogGalleryColumn	type_num, delete_overlay
xlDialogGalleryCustom	name_text
xlDialogGalleryDoughnut	type_num, delete_overlay
xlDialogGalleryLine	type_num, delete_overlay
xlDialogGalleryPie	type_num, delete_overlay
xlDialogGalleryRadar	type_num, delete_overlay
xlDialogGalleryScatter	type_num, delete_overlay
xlDialogGoalSeek	target_cell, target_value, variable_cell
xlDialogGridlines	x_major, x_minor, y_major, y_minor, z_major, z_minor, 2D_effect
xlDialogInsert	shift_num
xlDialogInsertObject	object_class, file_name, link_logical, display_icon_logical, icon_file, icon_number, icon_label
xlDialogInsertPicture	file_name, filter_number
xlDialogInsertTitle	chart, y_primary, x_primary, y_secondary, x_secondary
xlDialogLabelProperties	accel_text, accel2_text, 3d_shading
xlDialogListboxProperties	range, link, drop_size, multi_select, 3d_shading
xlDialogMacroOptions	macro_name, description, menu_on, menu_text, shortcut_on, shortcut_key, function_category, status_bar_text, help_id, help_file
xlDialogMailEditMailer	to_recipients, cc_recipients, bcc_recipients, subject, enclosures, which_address
xlDialogMailLogon	name_text, password_text, download_logical
xlDialogMailNextLetter
xlDialogMainChart	type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle
xlDialogMainChartType	type_num
xlDialogMenuEditor
xlDialogMove	x_pos, y_pos, window_text
xlDialogNew	type_num, xy_series, add_logical
xlDialogNote	add_text, cell_ref, start_char, num_chars
xlDialogObjectProperties	placement_type, print_object
xlDialogObjectProtection	locked, lock_text
xlDialogOpen	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
xlDialogOpenLinks	document_text1, document_text2, ..., read_only, type_of_link
xlDialogOpenMail	subject, comments
xlDialogOpenText	file_name, file_origin, start_row, file_type, text_qualifier, consecutive_delim, tab, semicolon, comma, space, other, other_char, field_info
xlDialogOptionsCalculation	type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values
xlDialogOptionsChart	display_blanks, plot_visible, size_with_window
xlDialogOptionsEdit	incell_edit, drag_drop, alert, entermove, fixed, decimals, copy_objects, update_links, move_direction, autocomplete, animations
xlDialogOptionsGeneral	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
xlDialogOptionsListsAdd	string_array
xlDialogOptionsListsAdd	import_ref, by_row
xlDialogOptionsTransition	menu_key, menu_key_action, nav_keys, trans_eval, trans_entry
xlDialogOptionsView	formula, status, notes, show_info, object_num, page_breaks, formulas, gridlines, color_num, headers, outline, zeros, hor_scroll, vert_scroll, sheet_tabs
xlDialogOutline	auto_styles, row_dir, col_dir, create_apply
xlDialogOverlay	type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle, series_num, auto
xlDialogOverlayChartType	type_num
xlDialogPageSetup	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
xlDialogPageSetup	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
xlDialogPageSetup	head, foot, left, right, top, bot, orient, paper_size, scale, quality, head_margin, foot_margin, pg_num
xlDialogParse	parse_text, destination_ref
xlDialogPasteSpecial	paste_num, operation_num, skip_blanks, transpose
xlDialogPasteSpecial	rowcol, titles, categories, replace, series
xlDialogPasteSpecial	paste_num
xlDialogPasteSpecial	format_text, pastelink_logical, display_icon_logical, icon_file, icon_number, icon_label
xlDialogPatterns	apattern, afore, aback, newui
xlDialogPatterns	lauto, lstyle, lcolor, lwt, hwidth, hlength, htype
xlDialogPatterns	bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, rounded, newui
xlDialogPatterns	bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, invert, apply, newfill
xlDialogPatterns	lauto, lstyle, lcolor, lwt, tmajor, tminor, tlabel
xlDialogPatterns	lauto, lstyle, lcolor, lwt, apply, smooth
xlDialogPatterns	lauto, lstyle, lcolor, lwt, mauto, mstyle, mfore, mback, apply, smooth
xlDialogPatterns	type, picture_units, apply
xlDialogPivotFieldGroup	start, end, by, periods
xlDialogPivotFieldProperties	name, pivot_field_name, new_name, orientation, function, formats
xlDialogPivotFieldUngroup
xlDialogPivotShowPages	name, page_field
xlDialogPivotTableWizard	type, source, destination, name, row_grand, col_grand, save_data, apply_auto_format, auto_page, reserved
xlDialogPlacement	placement_type
xlDialogPrint	range_num, from, to, copies, draft, preview, print_what, color, feed, quality, y_resolution, selection, printer_text, print_to_file, collate
xlDialogPrinterSetup	printer_text
xlDialogPrintPreview
xlDialogPromote	rowcol
xlDialogProperties	title, subject, author, keywords, comments
xlDialogProtectDocument	contents, windows, password, objects, scenarios
xlDialogPushbuttonProperties	default_logical, cancel_logical, dismiss_logical, help_logical, accel_text, accel_text2
xlDialogReplaceFont	font_num, name_text, size_num, bold, italic, underline, strike, color, outline, shadow
xlDialogRoutingSlip	recipients, subject, message, route_num, return_logical, status_logical
xlDialogRowHeight	height_num, reference, standard_height, type_num
xlDialogRun	reference, step
xlDialogSaveAs	document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec
xlDialogSaveCopyAs	document_text
xlDialogSaveNewObject
xlDialogSaveWorkbook	document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec
xlDialogSaveWorkspace	name_text
xlDialogScale	cross, cat_labels, cat_marks, between, max, reverse
xlDialogScale	min_num, max_num, major, minor, cross, logarithmic, reverse, max
xlDialogScale	cat_labels, cat_marks, reverse, between
xlDialogScale	series_labels, series_marks, reverse
xlDialogScale	min_num, max_num, major, minor, cross, logarithmic, reverse, min
xlDialogScenarioAdd	scen_name, value_array, changing_ref, scen_comment, locked, hidden
xlDialogScenarioCells	changing_ref
xlDialogScenarioEdit	scen_name, new_scenname, value_array, changing_ref, scen_comment, locked, hidden
xlDialogScenarioMerge	source_file
xlDialogScenarioSummary	result_ref, report_type
xlDialogScrollbarProperties	value, min, max, inc, page, link, 3d_shading
xlDialogSelectSpecial	type_num, value_type, levels
xlDialogSendMail	recipients, subject, return_receipt
xlDialogSeriesAxes	axis_num
xlDialogSeriesOrder	chart_num, old_series_num, new_series_num
xlDialogSeriesX	x_ref
xlDialogSeriesY	name_ref, y_ref
xlDialogSetControlValue	value
xlDialogSetPrintTitles	titles_for_cols_ref, titles_for_rows_ref
xlDialogSetUpdateStatus	link_text, status, type_of_link
xlDialogShowDetail	rowcol, rowcol_num, expand, show_field
xlDialogShowToolbar	bar_id, visible, dock, x_pos, y_pos, width, protect, tool_tips, large_buttons, color_buttons
xlDialogSize	width, height, window_text
xlDialogSort	orientation, key1, order1, key2, order2, key3, order3, header, custom, case
xlDialogSort	orientation, key1, order1, type, custom
xlDialogSortSpecial	sort_by, method, key1, order1, key2, order2, key3, order3, header, order, case
xlDialogSplit	col_split, row_split
xlDialogStandardFont	name_text, size_num, bold, italic, underline, strike, color, outline, shadow
xlDialogStandardWidth	standard_num
xlDialogStyle	bold, italic
xlDialogSubscribeTo	file_text, format_num
xlDialogSubtotalCreate	at_change_in, function_num, total, replace, pagebreaks, summary_below
xlDialogSummaryInfo	title, subject, author, keywords, comments
xlDialogTable	row_ref, column_ref
xlDialogTabOrder
xlDialogTextToColumns	destination_ref, data_type, text_delim, consecutive_delim, tab, semicolon, comma, space, other, other_char, field_info
xlDialogUnhide	window_text
xlDialogUpdateLink	link_text, type_of_link
xlDialogVbaInsertFile	filename_text
xlDialogVbaMakeAddin	filename_text
xlDialogVbaProcedureDefinition
xlDialogView3d	elevation, perspective, rotation, axes, height%, autoscale
xlDialogWindowMove	x_pos, y_pos, window_text
xlDialogWindowSize	width, height, window_text
xlDialogWorkbookAdd	name_array, dest_book, position_num
xlDialogWorkbookCopy	name_array, dest_book, position_num
xlDialogWorkbookInsert	type_num
xlDialogWorkbookMove	name_array, dest_book, position_num
xlDialogWorkbookName	oldname_text, newname_text
xlDialogWorkbookNew
xlDialogWorkbookOptions	sheet_name, bound_logical, new_name
xlDialogWorkbookProtect	structure, windows, password
xlDialogWorkbookTabSplit	ratio_num
xlDialogWorkbookUnhide	sheet_text
xlDialogWorkgroup	name_array
xlDialogWorkspace	fixed, decimals, r1c1, scroll, status, formula, menu_key, remote, entermove, underlines, tools, notes, nav_keys, menu_key_action, drag_drop, show_info
xlDialogZoom	magnification


SolverAdd Function

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.


SolverChange Function

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.


SolverDelete Function

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.


SolverFinish Function

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 [image] for example, ReportArray:= Array(1,3).


SolverFinishDialog Function

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 [image] for example, ReportArray:= Array(1,3).


SolverGet Function

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.


SolverLoad Function

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.


SolverOk Function

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.


SolverOkDialog Function

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.


SolverOptions Function

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 [image] 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 [image] for example, maximizing percent profit based on million-dollar investments. If False, Solver calculates without scaling the constraints. False is the default.


SolverSave Function

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.


SolverSolve Function

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.


SolverReset Function

Resets all cell selectionsand 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()


Import Method

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.


Play Method

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.


Record Method

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.


InputBox Function (Microsoft Excel)

In Microsoft Excel, the prompt string cannot contain more than 256 characters.


MsgBox Function (Microsoft Excel)

In Microsoft Excel, the prompt string cannot contain more than 256 characters.


Toolbar Button ID Values

The following table shows the available toolbar buttons and their button ID values.


Visual Basic Constants (Microsoft Excel)

Microsoft Excel contains built-in constants you use with methods and properties. These constants all begin with the letters "xl" and are documented with the methods or properties that use them.

You can use the Object Browser to browse the list of built-in constants. On the View menu, click Object Browser, click the Microsoft Excel library, and then click the Constants object. Scroll through the list in the Methods/Properties box to see the complete list of constants.


Trappable Errors (Microsoft Excel)

Microsoft Excel uses the following trappable errors, in addition to those used by Visual Basic. 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, search Help for the object name.

1001	'[Object]' does not have '[method name]' method

The method doesn't exist for this object. For more information, search Help 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, search Help 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, search Help 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, search Help 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, search Help 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, search Help for the property name.


SQLBind Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLClose Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLError Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLExecQuery Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLGetSchema Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLOpen Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLRequest Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLRetrieve Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


SQLRetrieveToFile Function

See Also	Example

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. For more information about Data Access Objects, see Data Access Overview.

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.


IncludeAlignment Property

True if the style includes the AddIndent, HorizontalAlignment, VerticalAlignment, WrapText, and Orientation properties. Read-write.


IncludeBorder Property

True if the style includes the Borders properties. Read-write.


IncludeFont Property

True if the style includes the Font property. Read-write.


IncludeNumber Property

True if the style includes the NumberFormat property. Read-write.


IncludePatterns Property

True if the style includes the Interior properties. Read-write.


IncludeProtection Property

True if the style includes the FormulaHidden and Locked protection properties. Read-write.


List of Worksheet Functions Available to Visual Basic

A

Acos

Acosh

And

Asin

Asinh

Atan2

Atanh

AveDev

Average

B

BetaDist

BetaInv

BinomDist

C

Ceiling

ChiDist

ChiInv

ChiTest

Choose

Clean

Combin

Confidence

Correl

Cosh

Count

CountA

CountBlank

CountIf

Covar

CritBinom

D

DAverage

Days360

Db

DCount

DCountA

Ddb

Degrees

DevSq

DGet

DMax

DMin

Dollar

DProduct

DStDev

DStDevP

DSum

DVar

DVarP

E

Even

ExponDist

F

Fact

FDist

Find

FindB

FInv

Fisher

FisherInv

Fixed

Floor

Forecast

Frequency

FTest

Fv

G

GammaDist

GammaInv

GammaLn

GeoMean

Growth

H

HarMean

HLookup

HypGeomDist

I

Index

Intercept

Ipmt

Irr

IsErr

IsError

IsLogical

IsNA

IsNonText

IsNumber

Ispmt

IsText

J

K

Kurt

L

Large

LinEst

Ln

Log

Log10

LogEst

LogInv

LogNormDist

Lookup

M

Match

Max

MDeterm

Median

Min

MInverse

MIrr

MMult

Mode

N

NegBinomDist

NormDist

NormInv

NormSDist

NormSInv

NPer

Npv

O

Odd

Or

P

Pearson

Percentile

PercentRank

Permut

Pi

Pmt

Poisson

Power

Ppmt

Prob

Product

Proper

Pv

Q

Quartile

R

Radians

Rank

Rate

Replace

ReplaceB

Rept

Roman

Round

RoundDown

RoundUp

RSq

S

Search

SearchB

Sinh

Skew

Sln

Slope

Small

Standardize

StDev

StDevP

StEyx

Substitute

Subtotal

Sum

SumIf

SumProduct

SumSq

SumX2MY2

SumX2PY2

SumXMY2

Syd

T

Tanh

TDist

Text

TInv

Transpose

Trend

Trim

TrimMean

TTest

U

USDollar

V

Var

VarP

Vdb

VLookup

W

Weekday

Weibull

X

Y

Z

ZTest


This is a worksheet function that is available only in Far East versions of Microsoft Excel.


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!


QueryGetData Function

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.


QueryGetDataDialog Function

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.


QueryRefresh Function

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.


MacroOptions Method

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.


HelpContextID Property

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.


HelpFile Property

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.


ActivePane Property

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.


Arrange Method

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.


DisplayAutomaticPageBreaks Property

True if automatic page breaks should be displayed for this sheet. Read-write.


DisplayFormulas Property

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.


DisplayGridlines Property

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.


DisplayHeadings Property

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.


DisplayOutline Property

True if outline symbols are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.


DisplayZeros Property

True if zero values are displayed. Read-write.

Remarks

This property applies only to worksheets and macro sheets.


FreezePanes Property

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.


GridlineColor Property

Returns or sets the gridline color as an RGB value. Read-write.


Panes Method

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.


SelectedSheets Method

Accessor. Returns a Sheets collection that represents all the selected sheets in the specified window.

Syntax

object.SelectedSheets

object

Required. The Window object.


Split Property

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.


SplitColumn Property

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.


SplitHorizontal Property

Returns or sets the location of the horizontal window split, in points (1/72 inch). Read-write.


SplitRow Property

Returns or sets the row number where the window is split into panes (the number of rows above the split). Read-write.


SplitVertical Property

Returns or sets the location of the vertical window split, in points (1/72 inch). Read-write.


CreateBackup Property

True if a backup will be created when this file is saved. Read-only.


DialogSheets Method

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.


Excel4IntlMacroSheets Method

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.


Excel4MacroSheets Method

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.


FileFormat Property

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.


HasPassword Property

True if the workbook has a protection password. Read-only.

Remarks

You can assign a protection password to a workbook with the SaveAs method.


Modules Method

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.


NewWindow Method

Creates a new window for the workbook, or a copy of the specified window.

Syntax

object.NewWindow

object

Required. The Window or Workbook object.


Open Method

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.


ProtectStructure Property

True if the order of the sheets in the workbook is protected. Read-only.


ProtectWindows Property

True if the windows of the workbook are protected. Read-only.


ReadOnly Property

True if the workbook has been opened as read-only. Read-only.


ReadOnlyRecommended Property

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.


RunAutoMacros Method

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.


SaveAs Method

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.


Saved Property

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.


Sheets Method

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.


Styles Method

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.


Worksheets Method

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.


WriteReserved Property

True if the workbook is write reserved. Read-only.

Remarks

Use the SaveAs method to set this property.


WriteReservedBy Property

Returns a string that names the user with current write permission for the workbook. Read-only.


TransitionExpEval Property

True if Microsoft Excel will use Lotus 1-2-3 expression evaluation rules for this worksheet. Read-write.


TransitionFormEntry Property

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.


Date1904 Property

True if this workbook uses the 1904 date system. Read-write.


DeleteNumberFormat Method

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.


DisplayDrawingObjects Property

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.


Drawings Method

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.


PrecisionAsDisplayed Property

True if calculations in this workbook will be done using only the precision of the numbers as they are displayed. Read-write.


SaveLinkValues Property

True if Microsoft Excel will save external link values with this workbook. Read-write.


ShowDataForm Method

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.


SpecialCells Method

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


StandardHeight Property

Returns the standard (default) height of all the rows in the worksheet, measured in points (1/72 inch). Read-only.


StandardWidth Property

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.


UpdateRemoteReferences Property

True if remote references will be updated for the workbook. Read-write.


UsedRange Property

Accessor. Returns a Range object that represents the used range on the specified worksheet. Read-only.


Microsoft Excel Objects


 Microsoft Excel Objects (Worksheet)


 Microsoft Excel Objects (Chart)


 Microsoft Excel Objects (DialogSheet)


Notes on Microsoft Excel Objects

Collection vs. Object

Objects shaded dark blue are contained in a collection. To return a single object in a collection, use an accessor method or property --- for example, use Workbooks("BUDGET94.XLS") to return a Workbook object that represents the Budget94 workbook.

Some Microsoft Excel objects which appear to be collections are actually single objects. There is a TickLabels object, for example, but no TickLabel object. Setting a property of a TickLabels object affects all the text labels along one chart axis. It is not possible to change a property for one individual label. Such objects are shaded as "Object only" on this chart (light blue).

Metacollections

A "metacollection" can contain objects of more than one type. The DrawingObjects collection is a metacollection. On any given sheet, this collection contains all the graphic objects (Rectangle objects, Oval objects, and so on) and all the controls (Button objects, EditBox objects, and so on) on that sheet.

Common Objects

Many of the objects on this chart contain some combination of the Border, Font, and Interior objects. To keep this chart easy to view, these common objects are not shown.


Visual Basic Equivalents A through C
Visual Basic Equivalents for Macro Functions and Commands

A

A1.R1C1(logical)	Application.ReferenceStyle = logical
ABSREF(ref_text, reference)	Range("reference").Offset(ref_text)
No direct equivalent. Use the Offset method and split the ref_text argument into numeric arguments.

ACTIVATE("BOOK1.XLS")	Windows("BOOK1.XLS").Activate ' or Workbooks("BOOK1.XLS").Activate
To activate the first window of a particular workbook, use the Workbooks form.

ACTIVATE("BOOK1.XLS:1")	Windows("BOOK1.XLS:1").Activate ' or Workbooks("BOOK1.XLS").Windows(1).Activate
To activate a specific window, use the number of the window with the Workbooks form.

ACTIVATE("BOOK1.XLS:1", pane_num)	Windows("BOOK1.XLS:1").Panes(pane_num).Activate
ACTIVATE(, pane_num)	ActiveWindow.Panes(pane_num).Activate
ACTIVATE.NEXT( )	ActiveWindow.ActivateNext
ACTIVATE.NEXT(workbook_text)	ActiveSheet.Next.Activate
ACTIVATE.PREV( )	ActiveWindow.ActivatePrevious
ACTIVATE.PREV(workbook_text)	ActiveSheet.Previous.Activate
ACTIVE.CELL( )	ActiveCell
ACTIVE.CELL.FONT(font, font style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count)	With ActiveCell.Characters(start_char, char_count).Font .Name = font .FontStyle = font_style .Size = size .Strikethrough = strikethrough .Superscript = superscript .Subscript = subscript .OutlineFont = outline .Shadow = shadow .Underline = underline .ColorIndex = color .Background = background End With
The normal parameter has no direct equivalent. You can set the font of the Normal style by copying the settings of the Normal style Font object, using ActiveWorkbook.Styles("Normal").Font.

ADD.ARROW( )	With ActiveChart.Lines.Add(0, 0, 72, 72) .ArrowHeadStyle = xlClosed End With
No direct equivalent. Add a line with a default set of coordinates by using the Add method of the Lines object, and then add the arrowhead to the new line.

ADD.BAR( )	Menubars.Add
ADD.BAR(bar_num)	Menubars(bar_num).Reset
ADD.CHART.AUTOFORMAT(name_text, desc_text)	Application.AddChartAutoFormat chart := ActiveChart, _ name := name_text, description := desc_text
ADD.COMMAND(bar_num, menu, command_ref, position1)	Menubars(bar_num).Menus(menu).MenuItems.Add _ caption := caption, onAction := macro, _ shortcutKey := key, before := position1
Adds a command to a menu. The command_ref reference area contains the information for the caption, onAction, and shortcutKey arguments. The status bar text and Help topic assigned to the command are determined by the status bar text and Help topic assigned to the OnAction macro. You set the macro options by using the Options button in the Macro dialog box (Tools menu, Macro command).

ADD.COMMAND(bar_num, menu, command_ref, position1, position2)	Menubars(bar_num).Menus(menu). _ MenuItems(position1).MenuItems.Add _ caption := caption, onAction := macro, _ shortcutKey := key, before := position2
Adds a command to a submenu.

ADD.COMMAND(bar_num, menu, command_ref, "Menu To Restore")	Menubars(bar_num).Menus(Menu ).MenuItems.Add _ caption := "Menu To Restore", restore := True
Restores a deleted menu command.

ADD.COMMAND(bar_num, menu, command_ref, position1, position2)	ShortcutMenus(shortcut_menu).MenuItems.Add _ caption := caption, onAction := macro, _ shortcutKey := key, before := position1
Adds a command to a shortcut menu. You access shortcut menus in Visual Basic by using the ShortcutMenus method with the appropriate constant.

ADD.LIST.ITEM(text, index_num)	Selection.AddItem(text := text, index := index_num)
ADD.MENU(bar_num, menu_ref, position1)	Menubars(bar_num).Menus.Add caption := caption, _ before := position1
Adds a menu. The menu_ref reference area contains information on the menu and its contents. In Visual Basic, you must explicitly add the contents of the menu by using the Add and AddMenu methods of the MenuItems object.

ADD.MENU(bar_num, menu_ref, position1, position2)	Menubars(bar_num).Menus(position1).MenuItems. _ AddMenu caption := caption, before := position2
Adds a submenu to an existing menu.

ADD.MENU(bar_num, "Menu To Restore")	Menubars(bar_num).Menus.Add caption := caption, _ restore := True
Restores a deleted menu.

ADD.OVERLAY( )
No direct equivalent. A secondary chart group (overlay) is created automatically when a series is added with a different chart type. See the Type property for the Series and ChartGroup objects.

ADD.TOOL(bar_id, position, tool_ref)	Toolbars(bar_id).ToolbarButtons.Add button := button, _ before := position, onAction := macro, _ pushed := pushed, enabled := enabled
Adds a custom toolbar button. The tool_ref reference area contains the information for the button, onAction, pushed, and enabled parameters. The status bar text and Help topic assigned to the button are determined by the status bar text and Help topic assigned to the OnAction macro. You set the macro options by using the Options button in the Macro dialog box (Tools menu, Macro command). The Attach Toolbars command on the Tools menu lets you associate static toolbars with a document.

ADD.TOOL(bar_id, position, button)	Toolbars(bar_id).ToolbarButtons.Add button := button, _ before := position
Adds a built-in toolbar button.

ADD.TOOLBAR(bar_name, tool_ref)	With Toolbars.Add(bar_name := bar_name) .ToolbarButtons.Add button := tool_ref End With
Adds a toolbar. The tool_ref area contains information on the toolbar and its buttons. In Visual Basic, you add buttons to the new toolbar by using the Add method of the ToolbarButtons object. This example adds a new toolbar and then adds a built-in button (tool_ref is a number in this syntax, not a reference).

ADDIN.MANAGER(1, addinname_text)	AddIns(addinname_text).Installed = True
ADDIN.MANAGER(2, addinname_text)	AddIns(addinname_text).Installed = False
ADDIN.MANAGER(3, addinname_text, copy_logical)	AddIns.Add filename := addinname_text, _ copyFile := copy_logical
ALERT(message_text, type_num, help_ref)	MsgBox prompt := message_text, buttons := type_num, _ helpfile := help_ref, context := help_ref
In Visual Basic, the Help filename and the Help context ID must be specified as a string and a number in the "HELPFILE!ID" format of ALERT.

ALIGNMENT(horiz_align, wrap, vert_align, orientation)	With Selection .HorizontalAlignment = horiz_align .WrapText = wrap .VerticalAlignment = vert_align .Orientation = orientation End With
APP.ACTIVATE.MICROSOFT(app_id)	Application.ActivateMicrosoftApp index := app_id
APP.ACTIVATE(title_text, wait_logical)	AppActivate title := title_text, wait := wait_logical
In Visual Basic, any window whose title begins with title_text is activated. An exact match is not required.

APP.MAXIMIZE( )	Application.WindowState = xlMaximized
APP.MINIMIZE( )	Application.WindowState = xlMinimized
APP.MOVE(x_num, y_num)	With Application .Left = x_num .Top = y_num End With
APP.RESTORE( )	Application.WindowState = xlNormal
APP.SIZE(x_num, y_num)	With Application .Width = x_num .Height = y_num End With
APP.TITLE(text)	Application.Caption = text
APPLY.NAMES( )	Range.ApplyNames
APPLY.STYLE(style_text)	Selection.Style = ActiveWorkbook.Styles(style_text)
ARGUMENT( )
No direct equivalent. Arguments to Visual Basic procedures are included as a part of the procedure declaration and header.

ARRANGE.ALL(arrange_num, active_doc, sync_horiz, sync_vert)	Windows.Arrange arrangeStyle := arrange_num, _ activeWorkbook := active_doc, _ syncHorizontal := sync_horiz, _ syncVertical := sync_vert
ASSIGN.TO.OBJECT(macro_ref)	Selection.OnAction := macro_ref
Macro_ref must specify the macro name as text, not as a reference.

ASSIGN.TO.TOOL(bar_id, position, macro_ref)	Toolbars(bar_id).ToolbarButtons(position). _ OnAction = macro_ref
Macro_ref must specify the macro name as text, not as a reference.

ATTACH.TEXT(1)	ActiveChart.HasTitle = True
ATTACH.TEXT(2)	ActiveChart.Axes(xlValue).HasTitle = True
ATTACH.TEXT(3)	ActiveChart.Axes(xlCategory).HasTitle = True
Attaches text to the primary category axis of a 2-D chart.

ATTACH.TEXT(3)	ActiveChart.Axes(xlSeries).HasTitle = True
Attaches text to the series axis of a 3-D chart.

ATTACH.TEXT(4, series_num, point_num)	ActiveChart.Series(series_num).Points(point_num). _ HasDataLabel = True
Attaches text to a particular series and data point. Also applies to 3-D chart types if the first argument is 5.

ATTACH.TEXT(4)	ActiveChart.Axes(xlCategory).HasTitle = True
Attaches text to the category axis of a 3-D chart.

ATTACH.TEXT(5)	ActiveChart.Axes(xlValue, xlSecondary).HasTitle = True
Attaches text to the secondary value axis of a 2-D chart.

ATTACH.TEXT(6)	ActiveChart.Axes(xlCategory, xlSecondary).HasTitle = True
Attaches text to the secondary category axis of a 2-D chart.

ATTACH.TOOLBARS( )	Application.Dialogs(xlDialogAttachToolbars).Show
AUTO.OUTLINE( )	Selection.AutoOutline
AXES(x_primary, y_primary, x_secondary, y_secondary)	With ActiveChart .HasAxis(xlCategory, 1) = x_primary .HasAxis(xlValue, 1) = y_primary .HasAxis(xlCategory, 2) = x_secondary .HasAxis(xlValue, 2) = y_secondary End With
Controls whether axes for 2-D chart types are on or off.

AXES(x_primary, y_primary, z_primary)	With ActiveChart .HasAxis(xlCategory) = x_primary .HasAxis(xlSeries) = y_primary .HasAxis(xlValue) = z_primary End With
Controls whether axes for 3-D chart types are on or off.

B

BEEP( )	Beep
BORDER(outline, , , , , , outline_color)	Selection.BorderAround lineStyle := outline_color, _ colorIndex := outline_color
Creates an outline border around the selected cells. In Visual Basic, use either the lineStyle or weight argument to the BorderAround method, depending on the border type you want.

BORDER(, left, , , , , , left_color, right_color)	With Selection.Borders(xlLeft) .Weight = left_color .ColorIndex = left_color End With
Sets the border for the left side of the selected cells (other sides are not modified). In Visual Basic, use the appropriate constant with the Borders method to select the border to modify. Use either the LineStyle or Weight property, depending on the border type you want.

BREAK( )	Exit For ' or Exit Do statement
To break out of a For...Next or For Each...Next loop, use Exit For. To break out of a Do...Loop statement, use Exit Do.

BRING.TO.FRONT( )	Selection.BringToFront
C

CALCULATE.DOCUMENT( )	ActiveSheet.Calculate
CALCULATE.NOW( )	Application.Calculate
CALCULATION(type_num, iter, max_num, max_change, update, precision, date_1904, calc_save, save_values, alt_exp, alt_form)	With Application .Calculation = type_num .Iteration = iter .MaxIterations = max_num .MaxChange = max_change .CalculateBeforeSave = calc_save End With With ActiveWorkbook .UpdateRemoteReferences = update .PrecisionAsDisplayed = precision .Date1904 = date_1904 .SaveLinkValues = save_values End With With ActiveSheet .TransitionExpEval = alt_exp .TransitionFormEntry = alt_form End With
CALL(register_id, argument1, ...)	Application.Run macro := register_id, argument1, ...
Calls a DLL function that was registered for use on the worksheet using the REGISTER function. In Visual Basic, use the Declare statement to register DLL functions if they're not going to be used on the worksheet.

CALL("SAMPLE.DLL", "MyFunction", "AIC", argument1, argument2, ...)	Declare Function MyFunction Lib "SAMPLE.DLL" _ (ByVal a As Integer, ByVal s As String) As Boolean ' Call the function using regular Visual Basic syntax MyFunction argument1, argument2
Calls a function in a DLL or code resource. In Visual Basic, the Declare statement registers DLL or code resource functions. The example shows how to declare and call a single function in SAMPLE.DLL, returning a Boolean value and taking an integer and a string parameter.

CALLER( )	Application.Caller
CANCEL.COPY(render_logical)	Application.CutCopyMode = render_logical
CANCEL.KEY(FALSE)	Application.EnableCancelKey = xlDisabled
CANCEL.KEY(TRUE)	Application.EnableCancelKey = xlInterrupt
CANCEL.KEY(TRUE, macro_ref)	Application.EnableCancelKey = xlErrorHandler
In Visual Basic, instead of specifying a procedure to run, cancel key trapping uses the standard Visual Basic run-time error trapping system. A trapped cancel key results in a trappable run-time error of code 18.

CELL.PROTECTION(locked, hidden)	With Selection .Locked = locked .FormulaHidden = hidden End With
CHANGE.LINK(old_text, new_text, type_of_link)	ActiveWorkbook.ChangeLink name := old_text, _ newName := new_text, type := type_of_link
CHART.ADD.DATA(ref, rowcol, titles, categories, replace, 1)	ActiveChart.SeriesCollection.Add source := ref, _ rowcol := rowcol, seriesLabels := titles, _ categoryLabels := categories, replace := replace
CHART.ADD.DATA(ref, rowcol, , categories, , 2)	ActiveChart.SeriesCollection.Extend source := ref, _ rowcol := rowcol, categoryLabels := categories
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)	ActiveChart.ChartWizard source := ref, _ gallery := gallery_num, type := type_num, _ plotBy := plot_by, categoryLabels := number_cats, _ seriesLabels := number_titles, _ hasLegend := legend, title := titles, _ categoryTitle := x_title, valueTitle := y_title, _ extraTitle := z_title
The categories and ser_titles arguments are not used in Microsoft Excel version 5.0 or later. Visual Basic supplies only the categoryLabels and seriesLabels arguments. The long argument has no equivalent, because the Visual Basic method is not interactive.

CHECKBOX.PROPERTIES(value, link, accel_text, accel2_text, 3d_shading)	With Selection .Value = value .LinkedCell = link .Display3DShading = 3d_shading .Accelerator = accel_text .PhoneticAccelerator = accel2_text End With
CHECK.COMMAND(bar_num, menu, command, check)	Menubars(bar_num).Menus(menu). _ MenuItems(command).Checked = check
Checks or unchecks a command on a menu.

CHECK.COMMAND(bar_num, menu, command, check, position)	Menubars(bar_num).Menus(menu). _ MenuItems(submenu). _ MenuItems(position).Checked = check
Checks or unchecks a command on a submenu.

CHECK.COMMAND(bar_num, menu, command, check)	ShortcutMenus(shortcut_menu). _ MenuItems(command).Checked = check
Checks or unchecks a command on a shortcut menu. You access shortcut menus in Visual Basic by using the ShortcutMenus method with the appropriate constant.

CLEAR(1)	Selection.Clear
Completely clears a worksheet range or chart area. You can omit the parameter 1.

CLEAR( )	Selection.Delete
Completely clears (deletes) the selected chart point, series, error bars, or trendline.

CLEAR( )	Selection.ClearFormats
Clears formats from the selected chart walls, floors, or plot area.

CLEAR(2)	Selection.ClearFormats
Clears formats from a worksheet range or from the selected chart item (not the entire chart).

CLEAR(3)	Selection.ClearContents
Clears contents from a worksheet range.

CLEAR(3)	ActiveChart.ChartArea.ClearContents
Clears all data series from an entire chart with nothing selected.

CLEAR(4)	Selection.ClearNotes
Clears notes from a worksheet range.

CLEAR.OUTLINE( )	Selection.ClearOutline
CLEAR.ROUTING.SLIP(FALSE)	ActiveWorkbook.HasRoutingSlip = False
CLEAR.ROUTING.SLIP(TRUE)	ActiveWorkbook.RoutingSlip.Reset
CLOSE(save_logical, route_logical)	ActiveWindow.Close saveChanges := save_logical, _ routeWorkbook := route_logical
To close a workbook regardless of how many windows it has open, use the Close method on the Workbook object. The Close method also includes a filename argument to specify the name that the workbook will be saved as if save_logical is TRUE.

CLOSE.ALL( )	Workbooks.Close
COLOR.PALETTE(file_text)	ActiveWorkbook.Colors = Workbooks(file_text).Colors
COLUMN.WIDTH(, reference, , 1)	Columns(reference).Hidden = True
Hides columns. If you're hiding the selection, use Selection.EntireColumn instead of the Columns method.

COLUMN.WIDTH(, reference, , 2)	Columns(reference).Hidden = False
Unhides columns.

COLUMN.WIDTH(, reference, , 3)	Columns(reference).AutoFit
Sizes the columns in reference to the width of the longest item in each column.

COLUMN.WIDTH(width_num, reference)	Columns(reference).ColumnWidth = width_num
Sets the column width to the specified value.

COLUMN.WIDTH(, reference, TRUE)	Columns(reference).ColumnWidth = _ ActiveSheet.StandardWidth
Sets the column width to the standard column width value.

COLUMN.WIDTH(, , , , standard_num)	ActiveSheet.StandardWidth = standard_num
Sets the standard column width for all columns on the worksheet.

COMBINATION(type_num)	ActiveChart.AutoFormat gallery := xlCombination, _ format := type_num
CONSOLIDATE(source_refs, function_num, top_row, left_col, create_links)	Selection.Consolidate sources := source_refs, function := function_num, topRow := top_row, _ leftColumn := left_col, createLinks := create_links
CONSTRAIN.NUMERIC(numeric_only)	Application.ConstrainNumeric = numeric_only
COPY( )	Selection.Copy
Copies the selected object, including ranges, chart items, and drawing objects.

COPY(from_reference, to_reference)	Range(from_reference).Copy to_reference
Copies a worksheet range from one location to another. If from_reference is omitted, use the Selection property instead of the Range method.

COPY.CHART(size_num)	ActiveChart.CopyPicture size := size_num
COPY.PICTURE(appearance_num, size_num, type_num)	Selection.CopyPicture _ appearance := appearance_num, _ format := type_num
Use this for all documents except charts.

COPY.PICTURE(appearance_num, size_num, type_num)	ActiveChart.CopyPicture _ appearance := appearance_num, _ size := size_num, format := type_num
Use this for charts.

COPY.TOOL(bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).CopyFace
CREATE.NAMES( )	Selection.CreateNames
CREATE.OBJECT(2, ref1, x_offset1, y_offset1, ref2, x_offset2, y_offset2)	With Range(ref1) left = .Left + x_offset1 top = .Top + y_offset1 End With With Range(ref2) width = (.Left + x_offset2) - left height = (.Top + y_offset2) - top End With ActiveSheet.Rectangles.Add left, top, width, height
Creates an unfilled rectangle object. Other objects are similar. Use the macro recorder to determine the exact form of the Visual Basic method required to create a particular drawing object. Note that Visual Basic uses absolute coordinates relative to the upper-left corner of the sheet, rather than the cell and offset positions of the Microsoft Excel 4.0 macro language. This example shows how to convert cell and offset coordinates into absolute coordinates.

CREATE.PUBLISHER(file_text, appearance, , formats)	If formats >= 8 Then hasValu = True formats = formats - 8 Else hasValu = False End If If formats >= 4 Then hasRtf = True formats = formats - 4 Else hasRtf = False End If If formats >= 2 Then hasBiff = True formats = formats - 2 Else hasBiff = False End If If formats >= 1 Then hasPict = True Else hasPict = False End If Selection.CreatePublisher edition := file_text, _ appearance := appearance, _ containsVALU := hasValu, containsRTF := hasRtf, _ containsBIFF := hasBiff, containsPICT := hasPict
Publishes a range. The formats argument is split into the containsBIFF, containsPICT, containsRTF, and containsVALU parameters in Visual Basic.

CREATE.PUBLISHER(file_text, appearance, size)	ActiveChart.CreatePublisher edition := file_text, _ appearance := appearance, size := size
Publishes a chart.

CUSTOM.REPEAT(macro_text, repeat_text)	Application.OnRepeat text := repeat_text, _ procedure := macro_text
Sets the repeat menu command for a custom command.

CUSTOM.REPEAT(, , record_text)	Application.RecordMacro xlmCode := record_text
Records arbitrary text from a custom command. Visual Basic has a basicCode parameter for recording Visual Basic code.

CUSTOM.UNDO(macro_text, undo_text)	Application.OnUndo text := undo_text, _ procedure := macro_text
CUT( )	Selection.Cut
Cuts the selected object to the Clipboard, including ranges, chart items, and drawing objects.

CUT(from_reference, to_reference)	Range(from_reference).Cut to_reference
Cuts a worksheet range from one location and pastes it into another. If from_reference is omitted, use the Selection property instead of the Range method.


Visual Basic Equivalents D through F
Visual Basic Equivalents for Macro Functions and Commands

D

DATA.DELETE( )
No direct equivalent.

DATA.FIND(logical)
No direct equivalent.

DATA.FIND.NEXT( )
No direct equivalent.

DATA.FIND.PREV( )
No direct equivalent.

DATA.FORM( )	ActiveSheet.ShowDataForm
DATA.LABEL(show_option, , show_key)	Selection.ApplyDataLabels type := show_option, _ legendKey := show_key
Inserts data labels for the selected point or series. If you're inserting data labels for the entire chart, use the ActiveChart property instead of the Selection property.

DATA.LABEL(show_option, auto_text, show_key)	With Selection .Type = show_option .AutoText = auto_text .ShowLegendKey = show_key End With
Sets data label properties for the selected label or set of labels.

DATA.SERIES(rowcol, type_num, date_num, step_value, stop_value, trend)	Selection.DataSeries rowcol := rowcol, _ type := type_num, date := date_num, _ step := step_value, stop := stop_value, _ trend := trend
DEFINE.NAME(name_text, refers_to, macro_type, shortcut_text, hidden, category, TRUE)	Names.Add name := ActiveSheet.Name & "!" &name_text, _ refersTo := refers_to, category := category, _ visible := Not hidden, macroType := macro_type, _ shortcutKey := shortcut_text
Defines a name for a particular sheet. The Visual Basic Add method defines a local name when the text of the Name begins with a sheet name followed by an exclamation point (for example, "Sheet1!SampleName"). This example defines the name on the active sheet, which must be a worksheet or macro sheet.

DEFINE.NAME(name_text, refers_to, macro_type, shortcut_text, hidden, category, FALSE)	Names.Add name := name_text, refersTo := refers_to, _ category := category, visible := Not hidden, _ macroType := macro_type, _ shortcutKey := shortcut_text
Defines a name for all sheets in the workbook. The Visual Basic Add method defines a global name when the text of the Name doesn't contain a sheet name and exclamation point (for example, "SampleName").

DEFINE.STYLE(style_text, number, font, alignment, border, pattern, protection)	With ActiveWorkbook.Styles.Add(name := style_text, _ basedOn := ActiveCell) .IncludeNumber = number .IncludeFont = font .IncludeAlignment = alignment .IncludeBorder = border .IncludePatterns = pattern .IncludeProtection = protection End With
Syntax 1: Defines a new style with the attributes of the active cell.

DEFINE.STYLE(style_text, 2, format_text)	With ActiveWorkbook.Styles(style_text) .NumberFormat = format_text End With
Syntax 2: Modifies the number formatting of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example.

DEFINE.STYLE(style_text, 3, name_text, size_num, bold, italic, underline, strike, color, outline, shadow, superscript, subscript)	With ActiveWorkbook.Styles(style_text).Font .Name = name_text .Size =  size_num .Bold = bold, .Italic = italic .Underline = underline .Strikethrough = strike .ColorIndex = color .OutlineFont = outline .Shadow = shadow .Superscript = superscript .Subscript = subscript End With
Syntax 3: Modifies the font settings of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example.

DEFINE.STYLE(style_text, 4, horiz_align, wrap, vert_align, orientation)	With ActiveWorkbook.Styles(style_text) .HorizontalAlignment = horiz_align .WrapText = wrap .VerticalAlignment = vert_align .Orientation = orientation End With
Syntax 4: Modifies the alignment settings of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example.

DEFINE.STYLE(style_text, 5, left, right, top, bottom, left_color, right_color, top_color, bottom_color)	With ActiveWorkbook.Styles(style_text).Borders With .Item(xlLeft) .LineStyle = left  .ColorIndex = left_color End With With .Item(xlRight) .Weight = right  .ColorIndex = right_color End With With .Item(xlTop) .LineStyle = top  .ColorIndex = top_color End With With .Item(xlBottom) .Weight = bottom .ColorIndex = bottom_color End With End With
Syntax 5: Modifies the border settings of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example. Use either the LineStyle or Weight property, depending on the border type you want.

DEFINE.STYLE(style_text, 6, apattern, afore, aback)	With ActiveWorkbook.Styles(style_text).Interior .ColorIndex = afore .Pattern = apattern .PatternColorIndex = aback End With
Syntax 6: Modifies the pattern settings of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example.

DEFINE.STYLE(style_text, 7, locked, hidden)	With ActiveWorkbook.Styles(style_text) .Locked = locked .FormulaHidden = hidden End With
Syntax 7: Modifies the protection settings of an existing style. To add a new style in Visual Basic, first use the Add method of the Styles object. See syntax 1 for an example.

DELETE.ARROW( )	Selection.Delete
Deletes the selected arrow object from the active chart.

DELETE.BAR(bar_num)	MenuBars(bar_num).Delete
DELETE.CHART.AUTOFORMAT( name_text)	Application.DeleteChartAutoFormat name := name_text
DELETE.COMMAND(bar_num, menu, command, subcommand)	MenuBars(bar_num).Menus(menu). _ MenuItems(command).Delete
Deletes a command from a menu.

DELETE.COMMAND(bar_num, menu, command, subcommand)	MenuBars(bar_num).Menus(menu). _ MenuItems(command). _ MenuItems(subcommand).Delete
Deletes a command from a submenu.

DELETE.COMMAND(bar_num, menu, command)	ShortcutMenus(shortcut_menu). _ MenuItems(command).Delete
Deletes a command from a shortcut menu. You access shortcut menus in Visual Basic by using the ShortcutMenus method with the appropriate constant.

DELETE.FORMAT(format_text)	ActiveWorkbook.DeleteNumberFormat format_text
DELETE.MENU(bar_num, menu)	MenuBars(bar_num).Menus(menu).Delete
Deletes a menu.

DELETE.MENU(bar_num, menu, submenu)	MenuBars(bar_num).Menus(submenu). _ MenuItems(submenu).Delete
Deletes a submenu.

DELETE.NAME(name_text)	Names(name_text).Delete
You access names defined only for the active sheet by preceding the text of the Name with the sheet name followed by an exclamation point (for example, "Sheet1!SampleName").

DELETE.OVERLAY( )	ActiveChart.ChartGroups(2).Type = _ ActiveChart.ChartGroups(1).Type
Deletes the overlay from the current chart. Microsoft Excel version 5.0 or later uses chart groups instead of overlays, so there is no direct Visual Basic equivalent. The example given merges the second chart group, or overlay, with the first chart group. This example works only if the chart overlay was created using Microsoft Excel 4.0 macros or was read from a Microsoft Excel 4.0 file.

DELETE.STYLE(style_text)	ActiveWorkbook.Styles(style_text).Delete
DELETE.TOOL(bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Delete
DELETE.TOOLBAR(bar_name)	Toolbars(bar_name).Delete
DEMOTE(1)	Selection.Rows.Group
Groups the rows of the range selection.

DEMOTE(2)	Selection.Columns.Group
Groups the columns of the range selection.

DEREF(reference)	Range(reference).Value
Like references in the Microsoft Excel 4.0 macro language, Visual Basic automatically returns the Value property in most circumstances where a Range object is used and a value is expected. Use the Value property to force a dereference if a Range object is expected.

DIALOG.BOX(dialog_ref)	Range(dialog_ref).DialogBox
Microsoft Excel version 5.0 or later supports a new style of dialog box that is visually edited. To use a new dialog box, insert a dialog sheet by pointing to Macro on the Insert menu and then clicking Dialog on the submenu.

DIRECTORY(path_text)	ChDir path_text
DISABLE.INPUT(logical)	Application.Interactive = Not logical
DISPLAY(formulas, gridlines, headings, zeros, color_num, reserved, outline, page_breaks, object_num)	With ActiveWindow .DisplayFormulas = formulas .DisplayGridlines = gridlines .DisplayHeadings = headings .DisplayZeros = zeros .GridlineColorIndex = color_num .DisplayOutline = outline End With ActiveSheet.DisplayAutomaticPageBreaks = page_breaks ActiveWorkbook.DisplayDrawingObjects = object_num
Controls view options for the active sheet and workspace.

DISPLAY(cell, formula, value, format, protection, names, precedents, dependents, note)	ActiveWindow.SetInfoDisplay cell, formula, value, _ mergeformat, protection, names, precedents, _ dependents, note
Controls options for the Info window. To directly access the Info window in Visual Basic, use Windows("Info").

DOCUMENTS( )	For Each wb in Workbooks answer = MsgBox "Print " & wb.Name & "?", vbYesNo If answer = vbYes Then wb.PrintOut End If Next
Returns an array that contains the names of all open workbooks that are not add-ins. In Visual Basic, use the Workbooks collection. Use a For Each...Next statement to iterate over each workbook in the collection. This example prompts the user to specify whether each open workbook should be printed, and then it prints the workbook if the user responds affirmatively.

DOCUMENTS(, match_text)	For Each wb In Workbooks If wb.Name Like match_text Then ' This workbook matches MsgBox "Match for " & wb.Name End If Next
Returns an array that contains the names matching the pattern match_text of all open workbooks that are not add-ins. Visual Basic doesn't have a direct equivalent, but this example simulates the name filtering by performing the filtering inside a loop.

DOCUMENTS(2)
No direct equivalent. You can access a particular open add-in by name by using the Workbooks method, but there's no way to get a collection of all open add-ins. Similarly, DOCUMENTS(3) doesn't have a Visual Basic equivalent.

DUPLICATE( )	Selection.Duplicate
E

ECHO(logical)	Application.ScreenUpdating = logical
EDIT.COLOR(color_num, red_value, green_value, blue_value)	ActiveWorkbooks.Colors(color_num) = _ RGB(red_value, green_value, blue_value)
EDIT.DELETE(1)	Selection.Delete xlToLeft
Deletes the cells in the selection. The EDIT.DELETE(2) command corresponds to the xlUp argument to the Delete method.

EDIT.DELETE(3)	Selection.EntireRow.Delete
Deletes the rows that contain the selection. Use the EntireColumn property instead of the EntireRow property for the EDIT.DELETE(4) command.

EDIT.OBJECT(verb_num)	Selection.Verb verb := verb_num
Edits the embedded or linked object. The no_pause argument has no equivalent in Visual Basic.

EDIT.REPEAT( )	Application.Repeat
EDIT.SERIES(series_num, name_ref, x_ref, y_ref, z_ref, plot_order)	ActiveChart.SeriesCollection(series_num) _ .PlotOrder = plot_order
No direct eqivalent. Adds a new series. Use the Add method of the SeriesCollection object to add a new series, and then set the Formula and PlotOrder properties to change series settings. The example shows how to access an existing series.

EDIT.TOOL(bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Edit
EDITBOX.PROPERTIES(validation_num, multiline_logical, vscroll_logical)	With Selection .InputType = (validation_num) .MultiLine = multiline_logical .DisplayVerticalScrollBar = vscroll_logical End With
EDITION.OPTIONS(edition_type, edition_name, reference, option, appearance, size, formats)	ActiveWorkbook.EditionOptions type := edition_type, _ option := , name := edition_name, _ reference := reference, appearance := _ appearance, chartSize := size, formats := formats
ELSE( )	Else keyword, part of an If...Then...Else statement
ELSE.IF(logical_test)	ElseIf keyword, part of an If...Then...Else statment
EMBED(object_class, item)
No direct equivalent. Displayed in the formula bar when an embedded object is selected, but cannot be entered on a macro sheet or used in a module.

ENABLE.COMMAND(bar_num, menu, command, enable)	MenuBars(bar_num).Menus(menu). _ MenuItems(command).Enabled = enable
Enables or disables a command on a menu.

ENABLE.COMMAND(bar_num, menu, command, enable, subcommand)	MenuBars(bar_num).Menus(menu). _ MenuItems(command). _ MenuItems(subcommand).Enabled = enable
Enables or disables a command on a submenu.

ENABLE.COMMAND(bar_num, menu, command, enable)	ShortcutMenus(shortcut_menu). _ MenuItems(command).Enabled = enable
Enables or disables a command on a shortcut menu. You access shortcut menusin Visual Basic by using the ShortcutMenus method with the appropriate constant.

ENABLE.TIPWIZARD(state)	Application.EnableTipWizard = state
ENABLE.TOOL(bar_id, position, enable)	Toolbars(bar_id).ToolbarButtons(position). _ Enabled = enable
END.IF( )	End If keyword, part of an If...Then...Else statement
ENTER.DATA(logical)	Application.DataEntryMode = logical
ERROR(FALSE)	On Error Resume Next Application.DisplayAlerts = False
Disables error checking and alert messages. In Visual Basic, the On Error statement causes errors to be ignored, and the DisplayAlerts property disables alert messages.

ERROR(TRUE)	On Error GoTo 0 Application.DisplayAlerts = True
Enables error checking and alert messages. Execution stops when a run-time error occurs. In Visual Basic, the On Error statement disables all error trapping and restores the default error alert, and the DisplayAlerts property enables alert messages.

ERROR(TRUE, macro_ref)	Sub ErrorsTrapped () ' Trap all errors, display alerts Application.DisplayAlerts = True On Error GoTo ErrorTrapper ' Code that potentially causes errors Exit Sub ErrorTrapper: ' Error recovery code ' Use the Resume statement to continue Resume Next End Sub
Traps errors and calls macro_ref when an error occurs. In Visual Basic, error handlers are not a separate procedure but are a labeled portion of the current procedure. The label is specified as the argument to the On Error statement.

ERRORBAR.X(include, type, amount, minus)	Selection.ErrorBar direction := xlX, include := include, _ type := type, amount := amount, _ minusValues := minus
ERRORBAR.Y(include, type, amount, minus)	Selection.ErrorBar direction := xlY, include := include, _ type := type, amount := amount, _ minusValues := minus
EVALUATE(formula_text)	Evaluate name := formula_text
EXEC(program_text, window_num)	Shell program_text, window_num
Starts an application in Microsoft Windows with an initial window state of window_num.

EXEC(program_text, , TRUE, preferred_size_only)	Shell program_text, 4
On the Macintosh, starts an application in the background. If the background argument is FALSE, specify 1 as the second parameter to the Shell function. The Shell method has no equivalent for the preferred_size_only argument.

EXECUTE(channel_num, execute_text)	DDEExecute channel_num, execute_text
EXTEND.POLYGON(array)	With Drawings.Add(x1, y1, x2, y2, closed) .AddVertex x3, y3 .AddVertex x4, y4 End With
Defines a polygon when there are more polygon vertices than can fit in a single CREATE.OBJECT command. In Visual Basic, use the AddVertex method as many times as necessary to add new vertices to a polygon. Note that the AddVertex coordinates are measured relative to the upper-left corner of the sheet or chart, not the upper-left corner of the rectangle that bounds the polygon.

EXTRACT(unique)
No direct equivalent. Use the AdvancedFilter method to perform extractions from database regions.

F

FCLOSE(file_num)	Close file_num
FILE.CLOSE(save_logical, route_logical)	ActiveWorkbook.Close saveChanges := save_logical, _ routeWorkbook := route_logical
FILE.DELETE(file_text)	Kill file_text
FILES(directory_text)	Dim arrayFiles() As String count = 0 f = Dir(directory_text) Do While Len(f) > 0 count = count + 1 ReDim Preserve arrayFiles(1 to count) arrayFiles(count) = f f = Dir() Loop
To get a list of all the files in a folder, you must sequentially call the Dir function in a loop, as shown in the example. Because a filename is available at each step of the loop, it may not be necessary for your application to build an array of files. This examples does build an array.

FILL.AUTO(destination_ref, copy_only)	Selection.AutoFill destination := destination_ref, _ type := copy_only
FILL.DOWN( )	Selection.FillDown
FILL.GROUP(type_num)	ActiveWindow.SelectedSheets.FillAcrossSheets _ range := Selection, type := type_num
FILL.LEFT( )	Selection.FillLeft
FILL.RIGHT( )	Selection.FillRight
FILL.UP( )	Selection.FillUp
FILTER( )	Selection.AutoFilter
FILTER(field_num, criteria1, operation, criteria2)	Selection.AutoFilter field := field_num, _ criteria1 := criteria1, operator := operation, _ criteria2 := criteria2
FILTER.ADVANCED(operation, list_ref, criteria_ref, copy_ref, unique)	Range(list_ref).AdvancedFilter action := operation, _ criteriaRange := criteria_ref unique := unique
FILTER.SHOW.ALL()	ActiveSheet.ShowAllData
FIND.FILE()	Application.FindFile
FONT(name_text, size_num)	With ActiveWorkbook.Styles("Normal").Font .Name = name_text .Size = size_num End With
FONT.PROPERTIES(font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal, background, start_char, char_count)	With Selection.Characters(start_char, char_count).Font .Name = font .FontStyle = font_style .Size = size .Strikethrough = strikethrough .Superscript = superscript .Subscript = subscript .OutlineFont = outline .Shadow = shadow .Underline = underline .ColorIndex = color .Background = background End With
Changes the font of the selected cells or text box. If both the start_char and char_count parameters are omitted, use Selection.Font in the With statement instead of Selection.Characters(start_char, char_count). The normal parameter has no direct equivalent. You can set the font of the Normal style by copying the settings of the Normal style Font object, using ActiveWorkbook.Styles("Normal").Font.

FOPEN(file_text, 1)	filenum = FreeFile Open file_text For Output Access Write As #filenum
Opens a file with read/write permissions for text input and ouput. In Visual Basic, you can open files for output only or for input only, not for both. This Visual Basic example opens the file for output only. Also, Visual Basic will always create the file if it doesn't already exist. Because of this, FOPEN(file_text, 3) translates to the same Visual Basic code as this example.

Visual Basic offers a richer set of file operations than the Microsoft Excel 4.0 macro language, allowing greater control over file input and output modes and access permissions. For information about the available modes, see Writing Data to Files and Open.

FOPEN(file_text, 2)	filenum = FreeFile Open file_text For Input Access Read As #filenum
Opens a file with read-only permission for text input.

FOR(counter_text, start_num, end_num, step_num)	For counter = start_num to end_num Step step_num
Increments a counter variable in a loop. In Visual Basic, the counter is a variable, not a defined name.

FOR.CELL(ref_name, area_ref)	For Each ref_name In area_ref
Iterates over a range of cells. In Visual Basic, the current cell ref_name is a variable, not a defined name.

FOR.CELL(ref_name, area_ref, TRUE)	For Each ref_name In area_ref If Not IsEmpty(ref_name.Value) Then ' Cell is non-blank End If Next
Iterates over a range of cells, skipping blank cells. The For Each...Next statement has no direct equivalent to the skip_blanks argument, so each cell is checked within the loop.

FORMAT.AUTO(format_num, number, font, alignment, border, pattern, width)	Selection.AutoFormat format := format_num, _ Number := number, Font := font, _ Alignment := alignment, _ Border := border, Pattern := pattern, _ Width := width
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)	With ActiveChart.ChartGroups(layer_num) .SubType = view .Overlap = overlap .FirstSliceAngle = angle .GapWidth = gap_width .DoughnutHoleSize = doughnut_size .AxisGroup =  axis_num .HasDropLines = drop .HasHiLoLines = hilo .HasUpDownBars = up_down .HasSeriesLines = series_line .HasRadarAxisLabels = labels .VaryByCategories = vary End With With ActiveChart .GapDepth = gap_depth .DepthPercent = chart_depth End With
Some arguments and properties may not apply to a particular chart type.

FORMAT.CHARTTYPE(1, , dimension, type_num)	Selection.Type = charttype
Sets the chart type of the selected series. Visual Basic doesn't distinguish 2-D and 3-D chart types; instead, it combines the dimension and type_num arguments into the Type property. The constants used for the Type property are named after the chart type (for example, xlRadar, xlLine, and xl3DArea).

FORMAT.CHARTTYPE(2, group_num, dimension, type_num)	ActiveChart.ChartGroups(group_num).Type = charttype
Sets the chart type of a particular chart group.

FORMAT.CHARTTYPE(3, , dimension, type_num)	ActiveChart.Type = charttype
Sets the chart type for the entire chart.

FORMAT.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow)	With Selection.Font .Name = name_text .Size = size_num .Bold = bold .Italic = italic .Underline = underline .Strikethrough = strike .ColorIndex = color .OutlineFont = outline .Shadow = shadow End With
Changes font settings for cells on worksheets or macro sheets.

FORMAT.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow, object_id_text, start_num, char_num)	With ActiveSheet.DrawingObjects(object_id_text). _ Characters(start_num, char_num).Font .Name = name_text .Size = size_num .Bold = bold .Italic = italic .Underline = underline .Strikethrough = strike .ColorIndex = color .OutlineFont = outline .Shadow = shadow End With
Changes font settings for text boxes and buttons on worksheets or macro sheets. If object_id_text is omitted, use the Selection property instead of DrawingObjects(object_id_text). If both start_num and char_num are omitted, you don't need to use Characters(start_num, char_num) in the statement.

FORMAT.FONT(color, backgd, apply, name_text, size_num, bold, italic, underline, strike, outline, shadow)	With Selection.Font .ColorIndex = color .Background = backgd .Name = name_text .Size = size_num .Bold = bold .Italic = italic .Underline = underline .Strikethrough = strike .OutlineFont = outline .Shadow = shadow End With
Changes font settings for unattached text in charts. The apply argument has no direct equivalent, but if TRUE, can be simulated by applying settings for the Font property of each Series object in the chart. Iterate over all series in the chart by using a For Each...Next loop with the SeriesCollection object of the active sheet.

FORMAT.LEGEND(position_num)	Selection.Position = position_num
FORMAT.MAIN(type_num, view, overlap, gap_width, vary, drop, hilo, angle, gap_depth, chart_depth, up_down, series_line, labels, doughnut_size)	With ActiveChart.ChartGroups(1) .Type = type_num .SubType = view .Overlap = overlap .GapWidth = gap_width .VaryByCategories = vary .HasDropLines = drop .HasHiLoLines = hilo .FirstSliceAngle = angle .HasUpDownBars = up_down .HasSeriesLines = series_line .HasRadarAxisLabels = labels .DoughnutHoleSize = doughnut_size End With With ActiveChart .GapDepth = gap_depth .DepthPercent = chart_depth End With
Some arguments and properties may not apply to a particular chart type. Microsoft Excel version 5.0 or later doesn't use a main chart and an overlay chart, but it provides for multiple chart types with chart groups. This example formats the first chart group, which is the number of the main chart for a chart originally saved in Microsoft Excel version 4.0.

FORMAT.MOVE(x_offset, y_offset, reference)	With Range(reference) xpos = .Left + x_offset ypos = .Top + y_offset End With With Selection .Left = xpos .Top = ypos End With
Moves a drawing object on a worksheet or macro sheet. Visual Basic coordinates are always relative to the upper-left corner of cell A1. This Visual Basic example adjusts the cell coordinates to be relative to A1. If reference is omitted, no adjustment is necessary.

FORMAT.MOVE(x_pos, y_pos)	With Selection .Left = x_pos adjVert = ActiveChart.ChartArea.Height - .Height .Top = adjVert - y_pos End With
Moves a drawing object or text on a chart. Visual Basic coordinates are based on the upper left of the object relative to the upper-left corner of the chart. Because FORMAT.MOVE coordinates are based on the lower-left corner of the object relative to the lower-left corner of the chart, a conversion is necessary.

FORMAT.MOVE(explosion_num)	Selection.Explosion = (explosion_num)
Moves a doughnut or pie chart slice.

FORMAT.NUMBER(format_text)	Selection.NumberFormat = format_text
FORMAT.OVERLAY(type_num, view, overlap, gap_width, vary, drop, hilo, angle, series_dist, series_num, up_down, series_line, labels)	With ActiveChart.ChartGroups(2) .Type = type_num .SubType = view .Overlap = overlap .GapWidth = gap_width .VaryByCategories = vary .HasDropLines = drop .HasHiLoLines = hilo .FirstSliceAngle = angle .HasUpDownBars = up_down .HasSeriesLines = series_line .HasRadarAxisLabels = labels End With
Some arguments and properties may not apply to a particular chart type. Microsoft Excel version 5.0 or later doesn't use a main chart and an overlay chart, but it provides for multiple chart types with chart groups. This example formats the second chart group, which is the number of the overlay chart for a chart originally saved in Microsoft Excel version 4.0.

The series_dist and series_num parameters have no direct equivalent in Visual Basic. Because Microsoft Excel version 5.0 or later can plot series with any chart group, use the Type property of the Series object to determine which chart group the series is plotted with.

FORMAT.SHAPE(vertex_num, insert, , x_offset, y_offset)	With Selection xpos = .Left + x_offset ypos = .Top + y_offset .Reshape vertex := vertex_num, insert := insert, _ left := xpos, top := ypos End With
Moves or inserts a vertex of a polygon drawing. FORMAT.SHAPE coordinates are relative to the upper-left corner of the rectangle that bounds the polygon when the reference parameter is omitted, as in this example. Visual Basic coordinates are relative to the upper-left corner of either cell A1 or the chart. To delete a vertex, specify False for insert and omit the left and top parameters.

FORMAT.SHAPE(vertex_num, insert, reference, x_offset, y_offset)	With Range(reference) xpos = .Left + x_offset ypos = .Top + y_offset End With Selection.Reshape vertex := vertex_num, insert := insert, _ left := xpos, top := ypos
Moves or inserts a vertex of a polygon drawing. The FORMAT.SHAPE coordinates are relative to the upper-left corner of reference. Visual Basic coordinates are relative to the upper-left corner of either cell A1 or the chart.

FORMAT.SIZE(width, height)	With Selection .Width = width .Height = height End With
Sizes objects in absolute coordinates.

FORMAT.SIZE(x_off, y_off, reference)	set ref = Range(reference) With Selection .Width = (ref.Left + x_off) - .Left .Height = (ref.Top + y_off) - .Top End With
Sizes objects relative to a worksheet cell. Visual Basic coordinates are always relative to the upper-left corner of cell A1, so a conversion is required.

FORMAT.TEXT(x_align, y_align, orient_num, auto_text, auto_size)	With Selection .HorizontalAlignment = x_align .VerticalAlignment = y_align .Orientation = orient_num .AutoText = auto_text .AutoSize = auto_size End With
The show_key and show_value arguments are not used by Microsoft Excel version 5.0 or later.

FORMULA(formula_text, reference)	Range(reference).FormulaR1C1 = formula_text
Enters a formula using R1C1-style references. To enter formulas using A1-style references in Visual Basic, use the Formula property instead of FormulaR1C1.

FORMULA(formula_text)	ActiveCell.FormulaR1C1 = formula_text
FORMULA.ARRAY(formula_text, reference)	Range(reference).FormulaArray = formula_text
Enters an array formula using R1C1-style references.

FORMULA.ARRAY(formula_text)	Selection.FormulaArray = formula_text
FORMULA.CONVERT(formula_text, from_a1, to_a1, to_ref_type, rel_to_ref)	Application.ConvertFormula formula := formula_text, _ fromReferenceStyle := from_a1, _ toReferenceStyle := to_a1, _ toAbsolute := to_ref_type, relativeTo := rel_to_ref
FORMULA.FILL(formula_text)	Selection.FormulaR1C1 = formula_text
FORMULA.FILL(formula_text, reference)	Range(reference) = formula_text
FORMULA.FIND(text, in_num, at_num, by_num, dir_num, match_case)	Cells.Find(what := text, after := ActiveCell, _ lookIn := in_num, lookAt := at_num, _ searchOrder := by_num, _ searchDirection := dir_num, _ matchCase := match_case).Activate
Searches for text in cells. If more than one cell was selected to restrict the range of the search, use the Selection property instead of the Cells method. Note that because the FIND command updates the selection, the result of the Find method is made the active cell.

FORMULA.FIND.NEXT( )	Cells.FindNext(after := ActiveCell).Activate
Searches for the next occurrence of text in cells. If more than one cell was selected at the start of the search, use the Selection property instead of the Cells method.

FORMULA.FIND.PREV( )	Cells.FindPrevious(after := ActiveCell).Activate
Searches for the previous occurrence of text in cells. If more than one cell was selected at the start of the search, use the Selection property instead of the Cells method.

FORMULA.GOTO(reference, corner)	Application.Goto reference := reference, scroll := corner
FORMULA.REPLACE(find_text, replace_text, look_at, look_by, FALSE, match_case)	Cells.Replace what := find_text, _ replacement := replace_text, lookAt := look_at, _ searchOrder := look_by, matchCase := match_case
Replaces text in cells. If more than one cell was selected to restrict the range of the search, use the Selection property instead of the Cells method.

FORMULA.REPLACE(find_text, replace_text, look_at, look_by, TRUE, match_case)	ActiveCell.Replace what := find_text, _ replacement := replace_text, lookAt := look_at, _ searchOrder := look_by, matchCase := match_case
Replaces text in the active cell only.

FPOS(file_num, position_num)	Seek file_num, position_num
Sets the current position in the file.

FPOS(file_num)	Seek(file_num)
Returns the current position in the file.

FREAD(file_num, num_chars)	Input(num_chars, file_num)
Reads bytes from a file. Note that the order of parameters is reversed. Unlike FREAD, the Input statement doesn't place restrictions on how many bytes can be read from a file at once. Microsoft Excel methods and properties, however, can accept only strings shorter than 256 characters. Strings that are longer than this are truncated when they're passed as an argument or property value.

FREADLN(file_num)	Dim resultString as String Line Input # file_num, resultString
Reads a line of text terminated by a newline character from a file. The Visual Basic Line Input statement doesn't return the read line; instead, it assigns the result to a variable that must be previously declared.

FREEZE.PANES(logical)	ActiveWindow.FreezePanes = True
FREEZE.PANES(TRUE, col_split, row_split)	With ActiveWindow .SplitRow = row_split .SplitColumn = col_split .FreezePanes = True End With
FSIZE(file_num)	LOF(file_num)
FULL(TRUE)	ActiveWindow.WindowState = xlMaximized
FULL(FALSE)	ActiveWindow.WindowState = xlNormal
FULL.SCREEN(logical)	Application.DisplayFullScreen = logical
FUNCTION.WIZARD()	Selection.FunctionWizard
FWRITE(file_num, text)	Print # file_num, text ;
Writes text to a file. Visual Basic doesn't place a limitation on string length, so the Print statement can write strings that are longer than 255 characters. Note the trailing semicolon character, which avoids writing out a trailing newline character.

FWRITELN(file_num, text)	Print # file_num, text
Writes text followed by a newline character to a file. Note that the Visual Basic equivalent doesn't have a trailing semicolon.


Visual Basic Equivalents G
Visual Basic Equivalents for Macro Functions and Commands

G

GALLERY.3D.AREA(type_num)	ActiveChart.AutoFormat gallery := xl3DArea, _ format := type_num
GALLERY.3D.BAR(type_num)	ActiveChart.AutoFormat gallery := xl3DBar, _ format := type_num
GALLERY.3D.COLUMN(type_num)	ActiveChart.AutoFormat gallery := xl3DColumn, _ format := type_num
GALLERY.3D.LINE(type_num)	ActiveChart.AutoFormat gallery := xl3DLine, _ format := type_num
GALLERY.3D.PIE(type_num)	ActiveChart.AutoFormat gallery := xl3DPie, _ format := type_num
GALLERY.3D.SURFACE(type_num)	ActiveChart.AutoFormat gallery := xl3DSurface, _ format := type_num
GALLERY.AREA(type_num)	ActiveChart.AutoFormat gallery := xlArea, _ format := type_num
Applies an autoformat to the active chart. The delete_overlay parameter has no direct equivalent in Visual Basic and Microsoft Excel version 5.0 or later. To format just the selected chart group, see the following example.

GALLERY.AREA(type_num, FALSE)	With Selection.Parent .Type = xlArea .SubType = type_num End With
Formats just the selected chart group. Use this syntax for all of the GALLERY.TYPE commands if the delete_overlay parameter is FALSE. The Visual Basic equivalent gets the chart group of the selected series with Selection.Parent, and then it changes the type and subtype as appropriate.

GALLERY.BAR(type_num)	ActiveChart.AutoFormat gallery := xlBar, _ format := type_num
GALLERY.COLUMN(type_num)	ActiveChart.AutoFormat gallery := xlColumn, _ format := type_num
GALLERY.CUSTOM(name_text)	ActiveChart.AutoFormat gallery := xlCustom, _ format := name_text
GALLERY.DOUGHNUT(type_num)	ActiveChart.AutoFormat gallery := xlDoughnut, _ format := type_num
GALLERY.LINE(type_num)	ActiveChart.AutoFormat gallery := xlLine, _ format := type_num
GALLERY.PIE(type_num)	ActiveChart.AutoFormat gallery := xlPie, _ format := type_num
GALLERY.RADAR(type_num)	ActiveChart.AutoFormat gallery := xlRadar, _ format := type_num
GALLERY.SCATTER(type_num)	ActiveChart.AutoFormat gallery := xlXYScatter, _ format := type_num
GET.BAR( )	ActiveMenuBar
Syntax 1:  Returns the ID of the active menu bar. The ActiveMenuBar property returns the MenuBar object that's active. Instead of using an ID, the object is manipulated directly.

GET.BAR(bar_num, menu, command)	MenuBars(bar_num).Menus(menu). _ MenuItems(command).Caption
Syntax 2:  Returns the name (as text) of a menu command by specifying the command argument as a number.

GET.BAR(bar_num, menu, command	MenuBars(bar_num).Menus(menu). _ MenuItems(command).Index
Syntax 2:  Returns the index of a menu command by specifying the command argument as text.

GET.BAR(bar_num, menu, command, subcommand)	MenuBars(bar_num).Menus(menu). _ MenuItems(command). _ MenuItems(subcommand).Caption
Syntax 2:  Returns the name (as text) or index number of a command on a submenu. In Visual Basic, use the Caption property of the MenuItem object to return the name as text, or use the Index property to return the index number.

GET.CELL(type_num, reference)	Range(reference).Resize(1, 1).Property
Returns information about a cell. If reference is specified, the Visual Basic equivalent is to use the appropriate method or property directly on a Range object constructed using the Range method. If reference is omitted, Visual Basic uses the active cell to return information. For clarity, the remaining translations of GET.CELL assume that reference is omitted.

GET.CELL(1)	ActiveCell.Address rowAbsolute := True, _ columnAbsolute := True, _ referenceStyle := Application.ReferenceStyle
Returns the absolute reference of the upper-left cell of the selection. Visual Basic is not dependent on the current reference style; you can choose the reference style you want to use. In this example, GET.CELL(1) is simulated by using the ReferenceStyle property to determine what style is returned.

GET.CELL(2)	ActiveCell.Row
GET.CELL(3)	ActiveCell.Column
GET.CELL(4)	valu = ActiveCell.Value If IsArray(valu) Then result = 64 ElseIf IsError(valu) Then result = 16 ElseIf TypeName(valu) = "Boolean" Then result = 4 ElseIf TypeName(valu) = "String" Then result = 2 Else result = 1 End If
Returns the type of the cell contents as a numeric code. In Visual Basic, it's probably not necessary to use this entire example, because you can construct your code to take advantage of the IsError, IsArray, and TypeName type comparison functions.

GET.CELL(5)	ActiveCell.Value
GET.CELL(6)	If Application.ReferenceStyle = xlA1 Then result = ActiveCell.Formula Else result = ActiveCell.FormulaR1C1 End If
Returns the formula of the cell, using the current reference style. Visual Basic isn't dependent on the current reference style; you can choose the reference style you want to use. In this example, GET.CELL(6) is simulated by using the ReferenceStyle property to determine what style is returned.

GET.CELL(7)	ActiveCell.NumberFormat
GET.CELL(8)	ActiveCell.HorizontalAlignment
GET.CELL(9)	ActiveCell.Borders(xlLeft).LineStyle ActiveCell.Borders(xlLeft).Weight
Returns the left border style of the cell. In Visual Basic, you specify the border style by using the LineStyle and Weight properties, depending on the border type that's selected. The same applies to GET.CELL(10) through GET.CELL(12) as well.

GET.CELL(10)	ActiveCell.Borders(xlRight).LineStyle ActiveCell.Borders(xlRight).Weight
GET.CELL(11)	ActiveCell.Borders(xlTop).LineStyle ActiveCell.Borders(xlTop).Weight
GET.CELL(12)	ActiveCell.Borders(xlBottom).LineStyle ActiveCell.Borders(xlBottom).Weight
GET.CELL(13)	ActiveCell.Interior.Pattern
GET.CELL(14)	ActiveCell.Locked
GET.CELL(15)	ActiveCell.FormulaHidden
GET.CELL(16)	cellWidth = ActiveCell.ColumnWidth If cellWidth = ActiveCell.Parent.StandardWidth Then isStandardWidth = True Else isStandardWidth = False End If
Unlike GET.CELL(16), the Visual Basic ColumnWidth property doesn't return an array. The example compares the cell width to the StandardWidth property of the worksheet to determine whether the cell is the standard width.

GET.CELL(17)	ActiveCell.RowHeight
GET.CELL(18)	ActiveCell.Font.Name
GET.CELL(19)	ActiveCell.Font.Size
GET.CELL(20)	ActiveCell.Font.Bold
GET.CELL(21)	ActiveCell.Font.Italic
GET.CELL(22)	ActiveCell.Font.Underline <> xlNone
GET.CELL23)	ActiveCell.Font.Strikethrough
GET.CELL(24)	ActiveCell.Font.ColorIndex
GET.CELL(25)	ActiveCell.Font.OutlineFont
GET.CELL(26)	ActiveCell.Font.Shadow
GET.CELL(27)	result = 0 If ActiveCell.EntireRow.PageBreak = xlManual Then result = result + 1 End If If ActiveCell.EntireColumn.PageBreak = xlManual Then result = result + 2 End If
Returns a result indicating whether a manual page break exists at the cell. In Visual Basic, rows and columns are individually examined for page breaks. The example builds a result value that's equivalent to GET.CELL(27).

GET.CELL(28)	ActiveCell.EntireRow.OutlineLevel
GET.CELL(29)	ActiveCell.EntireColumn.OutlineLevel
GET.CELL(30)	ActiveCell.EntireRow.Summary
GET.CELL(31)	ActiveCell.EntireColumn.Summary
GET.CELL(32)	Set containingBook = ActiveCell.Parent.Parent If containingBook.Sheets.Count = 1 Then ' Get bookname, strip off extension (if any) bookName = containingBook.Name For i = Len(bookName) To 1 Step -1 If Mid(bookName, i, 1) = "." Then bookName = Mid(bookName, 1, i - 1) Exit For End If Next x = StrComp(bookName, ActiveCell.Parent.Name, 1) If x <> 0 Then Goto BuildLongName result = containingBook.Name Else BuildLongName: result = "[" & containingBook.Name & _ "]" & ActiveCell.Parent.Name End If
Returns the name of the workbook and worksheet that contain the cell. The example constructs an exact equivalent of GET.CELL(32), which has special rules to provide backward compatability with Microsoft Excel version 4.0 behavior. In Visual Basic, it's not necessary to construct such an equivalent, because the Worksheet and Workbook objects that contain the cell are used instead of a text name.

GET.CELL(33)	ActiveCell.WrapText
GET.CELL(34)	ActiveCell.Borders(xlLeft).ColorIndex
GET.CELL(35)	ActiveCell.Borders(xlRight).ColorIndex
GET.CELL(36)	ActiveCell.Borders(xlTop).ColorIndex
GET.CELL(37)	ActiveCell.Borders(xlBottom).ColorIndex
GET.CELL(38)	ActiveCell.Interior.PatternColorIndex
GET.CELL(39)	ActiveCell.Interior.ColorIndex
GET.CELL(40)	ActiveCell.Style.Name
GET.CELL(41)	ActiveCell.FormulaLocal
GET.CELL(42)	ActiveCell.Left - _ Columns(ActiveWindow.ScrollColumn).Left
Returns the distance from the left edge of the window to the left edge of the cell. Visual Basic has no direct equivalent because the Left property of the Range object doesn't include the size of the window frame, the outline symbol area, or row and column headers. The example returns the distance from the left edge of the window to the left edge of the cell, not including items between the edge of the window and the edge of left-most column. This difference is usually not a translation issue because GET.CELL(42) is generally used only to determine the width of the cell using the expression GET.CELL(44) - GET.CELL(42), which is equivalent to ActiveCell.Width.

GET.CELL(43)	ActiveCell.Top - Rows(ActiveWindow.ScrollRow).Top
No direct equivalent. See remarks for GET.CELL(42).

GET.CELL(44)	(ActiveCell.Left + ActiveCell.Width) - _ Columns(ActiveWindow.ScrollColumn).Left
No direct equivalent. See remarks for GET.CELL(42).

GET.CELL(45)	(ActiveCell.Top + ActiveCell.Height) - _ Rows(ActiveWindow.ScrollRow).Top
No direct equivalent. See remarks for GET.CELL(42).

GET.CELL(46)	Len(ActiveCell.NoteText()) > 0
GET.CELL(47)	ExecuteExcel4Macro("GET.CELL(47)")
Returns a result indicating whether a cell contains a sound note. Visual Basic has no direct equivalent.

GET.CELL(48)	ActiveCell.HasFormula
GET.CELL(49)	ActiveCell.HasArray
GET.CELL(50)	ActiveCell.VerticalAlignment
GET.CELL(51)	ActiveCell.Orientation
GET.CELL(52)	ActiveCell.PrefixCharacter
GET.CELL(53)	ActiveCell.Text
GET.CELL(54)	ActiveCell.PivotTable.Name
GET.CELL(55)	ActiveCell.LocationInTable
GET.CELL(56)	ActiveCell.PivotField.Name
GET.CELL(57)	ActiveCell.Font.Superscript
GET.CELL(58)	ActiveCell.Font.FontStyle
GET.CELL(59)	ActiveCell.Font.Underline
GET.CELL(60)	ActiveCell.Font.Subscript
GET.CELL(61)	ActiveCell.PivotItem.Name
GET.CELL(62)	"[" & ActiveCell.Parent.Parent.Name & "]" & _ ActiveCell.Parent.Name
GET.CELL(63)	ActiveCell.Interior.ColorIndex
GET.CELL(64)	ActiveCell.Interior.PatternColorIndex
GET.CELL(65)	ActiveCell.AddIndent
GET.CELL(66)	ActiveCell.Parent.Parent.Name
GET.CHART.ITEM(x_y_index, point_index)
Returns position information for the selected chart item. Visual Basic has no equivalent for getting the position of data points or pie slices. If the selected object is a drawing object (such as an Oval or TextBox) use the Left, Top, Width, and Height properties to return position information. If the selected object is an arrow, Visual Basic has no means of determing which direction the arrowhead is facing, but you can get the position of the end points of the arrow.

GET.CHART.ITEM(1, 1)	Selection.Left
Returns the horizontal coordinate of the left edge of the selected legend, chart area, or plot area, or an area on an area chart. Use the same translation for GET.CHART.ITEM(1, 7) and GET.CHART.ITEM(1, 8).

GET.CHART.ITEM(1, 3)	Selection.Left + Selection.Width
Returns the horizontal coordinate of the right edge of the selected legend, chart area, or plot area, or an area on an area chart. Use the same translation for GET.CHART.ITEM(1, 4) and GET.CHART.ITEM(1, 5).

GET.CHART.ITEM(1, 2)	Selection.Left + (Selection.Width / 2)
Returns the horizontal coordinate of the middle of the selected legend, chart area, plot area, or rectangular data point, or an area on an area chart. Use the same translation for GET.CHART.ITEM(1, 6).

GET.CHART.ITEM(2, 1)	ActiveChart.ChartArea.Height - Selection.Top
Returns the vertical coordinate of the top of the selected legend, chart area, or plot area, or an area on an area chart. Use the same translation for GET.CHART.ITEM(2, 2) and GET.CHART.ITEM(2, 3) are identical. Note that the Visual Basic coordinate origin is in the upper-left corner, necessitating a conversion before an exact equivalent can be returned. Generally, you can write your code to avoid such conversions.

GET.CHART.ITEM(2, 7)	ActiveChart.ChartArea.Height - Selection.Top - _ Selection.Height
Returns the vertical coordinate of the bottom of the selected legend, chart area, or plot area, or an area on an area chart. Use the same translation for GET.CHART.ITEM(2, 6) and GET.CHART.ITEM(2, 5).

GET.CHART.ITEM(2, 8)	ActiveChart.ChartArea.Height - Selection.Top - _ (Selection.Height / 2)
Returns the vertical coordinate of the vertical midpoint of the selected legend, chart area, or plot area, or an area on an area chart. Use the same translation for GET.CHART.ITEM(2, 4).

GET.DEF(def_text, , type_num)	ActiveWorkbook.Names(refersTo := def_text).Name
Returns the name defined as the reference. Visual Basic has a Name object, and the Name property of that object is used to return the text value of the Name. Visual Basic doesn't have an equivalent to the type_num argument because all names are equally visible in Visual Basic; they're hidden only from the user. The Hidden property of the Name object indicates whether a particular name is hidden or not.

GET.DOCUMENT(type_num, name_text)	Sheets(name_text).Property
Returns information about a sheet. If name_text is specified, use the appropriate Visual Basic method or property directly on an object obtained using the Sheets method. If name_text is omitted, information is returned on the active sheet. For clarity, the remaining translations of GET.DOCUMENT assume that name_text is omitted.

Note that some Visual Basic equivalents use the object returned by the ActiveWorkbook property instead of a sheet object, reflecting the workbook organization of sheets in Microsoft Excel version 5.0 or later. See also GET.WORKBOOK.

GET.DOCUMENT(1)	If ActiveWorkbook.Sheets.Count = 1 Then ' Get bookname, strip off extension (if any) bookName = ActiveWorkbook.Name For i = Len(bookName) To 1 Step -1 If Mid(bookName, i, 1) = "." Then bookName = Mid(bookName, 1, i - 1) Exit For End If Next x = StrComp(bookName, ActiveSheet.Name, 1) If x <> 0 Then Goto BuildLongName result = ActiveWorkbook.Name Else BuildLongName: result = "[" & ActiveWorkbook.Name & _ "]" & ActiveSheet.Name End If
Returns the name of the active workbook and sheet. The example constructs an exact equivalent of GET.DOCUMENT(1), which has special rules to provide backward compatability with Microsoft Excel version 4.0 behavior. In Visual Basic, it's not necessary to construct such an equivalent because the Worksheet and Workbook objects are used instead of a text name.

GET.DOCUMENT(2)	ActiveWorkbook.Path
GET.DOCUMENT(3)	If ActiveWindow.Type = xlInfo Then result = 4 Else Select Case TypeName(ActiveSheet) Case "Chart" result = 2 Case "Module" result = 6 Case "DialogSheet" result = 7 Case Else If ActiveSheet.Type = xlWorksheet Then result = 1 Else result = 3 End If End Select End If
Returns the type of the active sheet as a number. In Visual Basic, you can compare types of sheets directly.

GET.DOCUMENT(4)
No direct equivalent. The GET.DOCUMENT command returns whether changes have been made to the current sheet. Visual Basic can only determine if changes have been made to the workbook, which is determined in the Microsoft Excel 4.0 macro language by GET.WORKBOOK(24).

GET.DOCUMENT(5)	ActiveWorkbook.ReadOnly
GET.DOCUMENT(6)	ActiveWorkbook.HasPassword
GET.DOCUMENT(7)	ActiveSheet.ProtectContents
GET.DOCUMENT(8)	ActiveWorkbook.ProtectWindows
GET.DOCUMENT(9)	ActiveChart.ChartGroups(1).Type
If the active sheet is a chart, returns the type of the main chart. Instead of using main and overlay charts, Microsoft Excel version 5.0 or later allows multiple chart groups on the same chart. The example returns the type of the first chart group, which is the number of the main chart if the chart was created in Microsoft Excel version 4.0.

GET.DOCUMENT(9)	ActiveSheet.UsedRange.Row
If the active sheet is a worksheet or macro sheet, returns the number of the first used row.

GET.DOCUMENT(10)	ActiveChart.ChartGroups(2).Type
If the active sheet is a chart, returns the type of the overlay chart. The example returns the type of the second chart group, which is the number of the overlay chart if the chart was created in Microsoft Excel version 4.0.

GET.DOCUMENT(10)	With ActiveSheet.UsedRange result = .Rows(.Rows.Count).Row End With
If the active sheet is a worksheet or macro sheet, returns the number of the last used row.

GET.DOCUMENT(11)	ActiveChart.ChartGroups(1).SeriesCollection.Count
If the active sheet is a chart, returns the number of series in the main chart. See remarks for GET.DOCUMENT(9) concerning main charts in Microsoft Excel version 5.0 or later.

GET.DOCUMENT(11)	ActiveSheet.UsedRange.Column
If the active sheet is a worksheet or macro sheet, returns the number of the first used column.

GET.DOCUMENT(12)	ActiveChart.ChartGroups(2).SeriesCollection.Count
If the active sheet is a chart, returns the number of series in the overlay chart. See remarks for GET.DOCUMENT(10) concerning overlay charts in Microsoft Excel version 5.0 or later.

GET.DOCUMENT(12)	With ActiveSheet.UsedRange result = .Columns(.Columns.Count).Column End With
If the active sheet is a worksheet or macro sheet, returns the number of the last used column.

GET.DOCUMENT(13)	ActiveWorkbook.Windows.Count
Returns the number of windows for the active workbook. Note that in Visual Basic, windows are accounted for per workbook, not per sheet.

GET.DOCUMENT(14)	Application.Calculation
GET.DOCUMENT(15)	Application.Iteration
GET.DOCUMENT(16)	Application.MaxIterations
GET.DOCUMENT(17)	Application.MaxChange
GET.DOCUMENT(18)	ActiveWorkbook.UpdateRemoteReferences
GET.DOCUMENT(19)	ActiveWorkbook.PrecisionAsDisplayed
GET.DOCUMENT(20)	ActiveWorkbook.Date1904
GET.DOCUMENT(21) through GET.DOCUMENT(29)
Returns attributes of the four default fonts in previous versions of Microsoft Excel. Visual Basic has no direct equivalents for these values because they are provided for macro compatibility only.

GET.DOCUMENT(30)	ActiveSheet.ConsolidationSources
GET.DOCUMENT(31)	ActiveSheet.ConsolidationFunction
GET.DOCUMENT(32)	ActiveSheet.ConsolidationOptions
GET.DOCUMENT(33)	Application.CalculateBeforeSave
GET.DOCUMENT(34)	ActiveWorkbook.ReadOnlyRecommended
GET.DOCUMENT(35)	ActiveWorkbook.WriteReserved
GET.DOCUMENT(36)	ActiveWorkbook.WriteReservedBy
GET.DOCUMENT(37)	ActiveWorkbook.FileFormat
GET.DOCUMENT(38)	ActiveSheet.Outline.SummaryRow
GET.DOCUMENT(39)	ActiveSheet.Outline.SummaryColumn
GET.DOCUMENT(40)	ActiveWorkbook.CreateBackup
GET.DOCUMENT(41)	ActiveWorkbook.DisplayDrawingObjects
GET.DOCUMENT(42)	Dim result() ReDim result(1 To ActiveSheet.DrawingObjects.Count) x = 1 For Each obj In ActiveSheet.DrawingObjects result(x) = obj.Name x = x + 1 Next
Returns an array of the drawing object names on the active sheet. You can directly access drawing objects by using the DrawingObjects collection. The example uses the For Each...Next statement to construct an array of drawing object names that enumerates every drawing object. Also, you can directly access drawing objects of a particular type (for example, only Rectangles or only Ovals).

GET.DOCUMENT(43)	ActiveWorkbook.SaveLinkValues
GET.DOCUMENT(44)	ActiveSheet.ProtectDrawingObjects
GET.DOCUMENT(45)	ExecuteExcel4Macro("GET.DOCUMENT(45)")
Indicates whether the windows of the current document are synchronized. Visual Basic has no equivalent because Microsoft Excel version 5.0 or later supports synchronized windows for macro compatability only.

GET.DOCUMENT(46)	ExecuteExcel4Macro("INDEX(GET.DOCUMENT(46),,1)")
Returns settings used by LINE.PRINT. Visual Basic doesn't support LINE.PRINT. The ExecuteExcel4Macro method cannot return an array, so indexing is required to retrieve the elements of the array one at a time.

GET.DOCUMENT(47)	ActiveSheet.TransitionExpEval
GET.DOCUMENT(48)	ActiveSheet.StandardWidth
GET.DOCUMENT(49)	ActiveSheet.PageSetup.FirstPageNumber
GET.DOCUMENT(50)	ExecuteExcel4Macro("GET.DOCUMENT(50)")
Returns the number of pages that will be printed with current settings for the active sheet, excluding notes. Visual Basic has no equivalent.

GET.DOCUMENT(51)	ExecuteExcel4Macro("GET.DOCUMENT(51)")
Returns the number of pages of notes that will be printed. Visual Basic has no equivalent.

GET.DOCUMENT(52)	With ActiveSheet.PageSetup left = .LeftMargin right = .RightMargin top = .TopMargin bottom = .BottomMargin End With
Returns the printing margin settings. In Visual Basic, you can access these settings directly as properties. The values are always in points. The example saves the property values but doesn't create an array.

GET.DOCUMENT(53)	ActiveSheet.PageSetup.Orientation
GET.DOCUMENT(54)	With ActiveSheet.PageSetup result = "&L" & .LeftHeader result = result & "&C" & .CenterHeader result = result & "&R" & .RightHeader End With
GET.DOCUMENT(55)	With ActiveSheet.PageSetup result = "&L" & .LeftFooter result = result & "&C" & .CenterFooter result = result & "&R" & .RightFooter End With
GET.DOCUMENT(56)	Array(ActiveSheet.PageSetup.CenterHorizontally, _ ActiveSheet.PageSetup.CenterVertically)
GET.DOCUMENT(57)	ActiveSheet.PageSetup.PrintHeadings
GET.DOCUMENT(58)	ActiveSheet.PageSetup.PrintGridlines
GET.DOCUMENT(59)	ActiveSheet.PageSetup.BlackAndWhite
GET.DOCUMENT(60)	ActiveSheet.PageSetup.ChartSize
GET.DOCUMENT(61)	ActiveSheet.PageSetup.Order
GET.DOCUMENT(62)	ActiveSheet.PageSetup.Zoom
GET.DOCUMENT(63)	Array(ActiveSheet.PageSetup.FitToPagesWide, _ ActiveSheet.PageSetup.FitToPagesTall)
GET.DOCUMENT(64)	Dim rNums() As Integer count = 0 For Each row In ActiveSheet.UsedRange.Rows If row.PageBreak <> xlNone Then count = count + 1 ReDim Preserve rNums(1 To count) rNums(count) = row.Row End If Next
Returns an array of row numbers correspondIng to rows immediately below either a manual or automatic page break. Visual Basic has no direct equivalent. The example builds an equivalent array from the used range of the sheet.

GET.DOCUMENT(65)	Dim cNums() As Integer count = 0 For Each col In ActiveSheet.UsedRange.Columns If col.PageBreak <> xlNone Then count = count + 1 ReDim Preserve cNums(1 To count) cNums(count) = col.Column End If Next
Returns an array of column numbers corresponding to columns immediately to the right of either a manual or automatic page break. Visual Basic has no direct equivalent. The example builds an equivalent array from the used range of the sheet.

GET.DOCUMENT(66)	ActiveSheet.TransitionFormEntry
GET.DOCUMENT(67)	True
Visual Basic always returns True because Microsoft Excel version 5.0 or later doesn't support unbound workbooks.

GET.DOCUMENT(68)	ActiveSheet.Parent.Name
GET.DOCUMENT(69)	ActiveSheet.DisplayAutomaticPageBreaks
GET.DOCUMENT(70)	Dim result() ReDim result(1 To ActiveSheet.PivotTables.Count) x = 1 For Each t In ActiveSheet.PivotTables result(x) = t.Name x = x + 1 Next
Returns an array of the names of all PivotTables on the active sheet. Visual Basic has no direct equivalent. The PivotTables collection can be used to iterate all PivotTables. The example builds an array of PivotTable names by using the PivotTables collection.

GET.DOCUMENT(71)	Dim result() ReDim result(1 To ActiveWorkbook.Styles.Count) x = 1 For Each s In ActiveWorkbook.Styles result(x) = s.Name x = x + 1 Next
Returns an array of the names of all styles in the current workbook. Visual Basic has no direct equivalent. The Styles collection can be used to iterate all styles. The example builds an array of style names by using the Styles collection.

GET.DOCUMENT(72)	Dim result() ReDim result(1 To ActiveChart.ChartGroups.Count) x = 1 For Each g In ActiveChart.ChartGroups result(x) = g.Type x = x + 1 Next
Returns an array of the chart group types in the current chart. Visual Basic has no direct equivalent. The ChartGroups collection can be used to iterate all groups. The example builds an array of chart group types by using the ChartGroups collection.

GET.DOCUMENT(73)	Dim result() ReDim result(1 To ActiveChart.ChartGroups.Count) x = 1 For Each g In ActiveChart.ChartGroups seriesCount = 0 For Each s In g.SeriesCollection seriesCount = seriesCount + 1 Next result(x) = seriesCount x = x + 1 Next
Returns an array of the count of series in each chart group in the current chart. Visual Basic has no direct equivalent. The example builds an array of the series count for each chart group by iterating the ChartGroup collection.

GET.DOCUMENT(74)	ActiveSheet.Focus
GET.DOCUMENT(75)	ActiveSheet.DefaultButton
GET.DOCUMENT(76)	"[" & ActiveSheet.Parent.Name & "]" & ActiveSheet.Name
GET.DOCUMENT(77)	ActiveSheet.PageSetup.PaperSize
GET.DOCUMENT(78)	ActiveSheet.PageSetup.PrintQuality
GET.DOCUMENT(79)	ActiveSheet.PageSetup.Draft
GET.DOCUMENT(80)	ActiveSheet.PageSetup.PrintNotes
GET.DOCUMENT(81)	ActiveSheet.PageSetup.PrintArea
GET.DOCUMENT(82)	Array(ActiveSheet.PageSetup.PrintTitleRows, _ ActiveSheet.PageSetup.PrintTitleColumns)
Returns the reference addresses of the print title rows and columns. Visual Basic always returns the address in A1-style notation.

GET.DOCUMENT(83)	ActiveSheet.ProtectScenarios
GET.DOCUMENT(84)	ActiveSheet.CircularReference
GET.DOCUMENT(85)	ActiveSheet.FilterMode
GET.DOCUMENT(86)	ActiveSheet.AutoFilterMode
GET.DOCUMENT(87)	ActiveSheet.Index
GET.DOCUMENT(88)	ActiveSheet.Parent.Name
GET.FORMULA(reference)	Range(reference).Resize(1, 1).FormulaR1C1
Returns the formula of a the upper-left cell of the referenced range.

GET.FORMULA("Picture 1")	ActiveSheet.Pictures("Picture 1").Formula
Returns the formula of a linked picture created with the Camera tool. Visual Basic returns the formula using A1-style references.

GET.FORMULA("S3")	ActiveChart.SeriesCollection(3).FormulaR1C1
Returns the series formula.

GET.LINK.INFO(link_text, type_num, type_of_link, reference)	ActiveWorkbook.LinkInfo(name := link_text, _ linkInfo := type_num, type := type_of_link, _ editionRef := reference)
GET.NAME("!Profit", 1)	ActiveWorkbook.Names("Profit").RefersToR1C1
Returns the definition of a name defined in the active workbook.

GET.NAME("[BOOK1.XLS]Sheet1!Profit", 1)	Workbooks("BOOK1").Names("Profit").RefersToR1C1
Returns the definition of a name defined in a particular workbook.

GET.NAME("Sheet1!Profit", 2)	Function DefinedLocally(wb As Object, sheet As String, _   n As String) DefinedLocally = True On Error Goto NotDefined wb.Names(sheet & "!" & n) Exit Function NotDefined: DefinedLocally = False Exit Function End Function
Returns TRUE if the name is defined only for the specified sheet, or returns FALSE if the name is defined for the entire workbook. Visual Basic has no direct equivalent, but if the name of the name contains an exclamation point, the name is defined only for the sheet. The example is a function that tries to retrieve the name with an exclamation point. If the name cannot be retrieved with an exclamation point, the name must be defined for the entire workbook.

GET.NOTE(cell_ref, start_char, num_chars)	Range(cell_ref).NoteText(start := start_char, _ length := num_chars)
Returns the text of a cell note. Use the ActiveCell property instead of the Range method if the cell_ref argument is omitted.

GET.OBJECT(type_num, object_id_text, start_num, count_num)	ActiveSheet.DrawingObjects(object_id_text).Property
Returns information about a drawing object. If object_id_text is specified, use the appropriate Visual Basic method or property directly on an object obtained using the DrawingObjects method. If object_id_text is omitted, Visual Basic returns information on the selected object. For clarity, the remaining translations of GET.OBJECT assume that object_id_text is omitted.

The start_num, count_num, and item_index arguments are used for certain values of type_num. This translation list includes these arguments only where appropriate.

GET.OBJECT(1)	Select Case TypeName(Selection) Case "GroupObject" result = 0 Case "Line" result = 1 Case "Rectangle" result = 2 Case "Oval" result = 3 Case "Arc" result = 4 Case "ChartObject" result = 5 Case "TextBox" result = 6 Case "Button" result = 7 Case "Picture", "OLEObject" result = 8 Case "Drawing" result = 9 Case "CheckBox" result = 11 Case "OptionButton" result = 12 Case "EditBox" result = 13 Case "Label" result = 14 Case "DialogFrame" result = 15 Case "Spinner" result = 16 Case "ScrollBar" result = 17 Case "ListBox" result = 18 Case "GroupBox" result = 19 Case "DropDown" result = 20 Case Else result = CVErr(xlErrValue) End Select
Determines the type of the selected object. Visual Basic has no direct equivalent. This example computes the equivalent by examining the object type name. Visual Basic cannot detect the difference between open and closed polygons.

GET.OBJECT(2)	Selection.Locked
GET.OBJECT(3)	Selection.ZOrder
GET.OBJECT(4)	Selection.TopLeftCell
GET.OBJECT(5)	Selection.Left - Selection.TopLeftCell.Left
Returns the distance from the upper-left cell to the left edge of the object. Visual Basic has no direct equivalent because it measures drawing object coordinates relative to the upper-left corner of the sheet. The example converts the sheet-relative coordinates to cell-relative coordinates.

GET.OBJECT(6)	Selection.Top - Selection.TopLeftCell.Top
Returns the distance from the upper-left cell to the top edge of the object. Visual Basic has no direct equivalent because it measures drawing object coordinates relative to the upper-left corner of the sheet. The example converts the sheet-relative coordinates to cell-relative coordinates.

GET.OBJECT(7)	Selection.BottomRightCell
GET.OBJECT(8)	(Selection.Left + Selection.Width) - _ Selection.BottomRightCell.Left
Returns the distance from the upper-left corner of the lower-right cell to the right edge of the object. Visual Basic has no direct equivalent because it measures drawing object coordinates relative to the upper-left corner of the sheet. The example converts the sheet-relative coordinates to cell-relative coordinates.

GET.OBJECT(9)	(Selection.Top + Selection.Height) - _ Selection.BottomRightCell.Top
Returns the distance from the upper-left corner of the lower-right cell to the bottom edge of the object. Visual Basic has no direct equivalent because it measures drawing object coordinates relative to the upper-left corner of the sheet. The example converts the sheet-relative coordinates to cell-relative coordinates.

GET.OBJECT(10)	Selection.OnAction
GET.OBJECT(11)	Selection.Placement
GET.OBJECT(12, , start_num, count_num)	Selection.Characters(start_num, count_num)
GET.OBJECT(13, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Name
GET.OBJECT(14, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Size
GET.OBJECT(15, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Bold
GET.OBJECT(16, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Italic
GET.OBJECT(17, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Underline _ <> xlNone
GET.OBJECT(18, , start_num, count_num)	Selection.Characters(start_num, ount_num).Font.Strikethrough
GET.OBJECT(19, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.OutlineFont
GET.OBJECT(20, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.Shadow
GET.OBJECT(21, , start_num, count_num)	Selection.Characters(start_num, count_num).Font.ColorIndex
GET.OBJECT(22)	Selection.HorizontalAlignment
GET.OBJECT(23)	Selection.VerticalAlignment
GET.OBJECT(24)	Selection.Orientation
GET.OBJECT(25)	Selection.AutoSize
GET.OBJECT(26)	Selection.Visible
GET.OBJECT(27)	lstyle = Selection.Border.LineStyle If lstyle = xlAutomatic Then result = 1 ElseIf lstyle = xlNone Then result = 2 Else result = 0 End If
Returns the type of the border or line. In Visual Basic, use the LineStyle property directly.

GET.OBJECT(28)	Selection.Border.LineStyle
Returns the border or line style.

GET.OBJECT(29)	Selection.Border.ColorIndex
GET.OBJECT(30)	Selection.Border.Weight
GET.OBJECT(31)	pat = Selection.Interior.Pattern If pat = xlAutomatic Then result = 1 ElseIf pat = xlNone Then result = 2 Else result = 0 End If
Returns the type of fill. In Visual Basic, use the Pattern property directly.

GET.OBJECT(32)	Selection.Interior.Pattern
GET.OBJECT(type_num, object_id_text, start_num, count_num)	Selection.Interior.PatternColorIndex
GET.OBJECT(34)	Selection.Interior.ColorIndex
GET.OBJECT(35)	Selection.ArrowHeadWidth
GET.OBJECT(36)	Selection.ArrowHeadLength
GET.OBJECT(37)	Selection.ArrowHeadStyle
GET.OBJECT(38)	Selection.RoundedCorners
GET.OBJECT(39)	Selection.Shadow
GET.OBJECT(40)	Selection.LockedText
GET.OBJECT(41)	Selection.PrintObject
GET.OBJECT(42)	Selection.Left - Columns(ActiveWindow.ScrollColumn).Left
Returns the distance from the left edge of the window to the left edge of the selected object. Visual Basic has no direct equivalent because the Left property of drawing objects doesn'tinclude the size of the window frame, the outline symbol area, or row and column headers. The example returns the distance from the left edge of the window, not counting such items between the edge of the window and the edge of the leftmost column. This difference is usually not a translation issue because GET.OBJECT(42) is generally used only to determine the width of the object using the expression GET.OBJECT(44) - GET.OBJECT(42), which is equivalent to Selection.Width.

GET.OBJECT(43)	Selection.Top - Rows(ActiveWindow.ScrollRow).Top
No direct equivalent. See remarks for GET.OBJECT(42).

GET.OBJECT(44)	(Selection.Left + Selection.Width) - _ Columns(ActiveWindow.ScrollColumn).Left
No direct equivalent. See remarks for GET.OBJECT(42).

GET.OBJECT(45)	(Selection.Top + Selection.Height) - _ Rows(ActiveWindow.ScrollRow).Top
No direct equivalent. See remarks for GET.OBJECT(42).

GET.OBJECT(46)	UBound(Selection.Vertices, 1)
Returns the number of vertices in a polygon. Visual Basic cannot determine the number of vertices if there are more than 255 vertices in a polygon, in which case 255 is always returned. In such cases, use ExecuteExcel4Macro("GET.OBJECT(46)").

GET.OBJECT(47, , start_num)	Selection.Vertices
Returns an array of polygon vertices starting at vertex start_num. Visual Basic has no equivalent for the start_num parameter, which is always assumed to be 1. Also, the Visual Basic Vertices property cannot return more than 255 vertices as an array. To access the vertices numbered beyond 255, retrieve a single coordinate by passing row and column index parameters to the Vertices property. For example, Selection.Vertices(500, 1) retrieves the x coordinate of the five hundredth vertex.

GET.OBJECT(48)	Selection.Formula
Returns the formula of the cell linked to a text box or button. Visual Basic always returns an A1-style reference.

GET.OBJECT(48)	Selection.LinkedCell
Returns the formula of the cell linked to an on-sheet control. Visual Basic always returns an A1-style reference.

GET.OBJECT(49)	ExecuteExcel4Macro("GET.OBJECT(49)")
Returns the creation index of an object. The creation index is the number that follows the default name of the object. For example "Line 5" has a creation index of 5. Visual Basic has no equivalent.

GET.OBJECT(50)	TypeName(Selection)
Returns the class name of the object as text. The example returns the Visual Basic object name. You can create an exact equivalent by using a comparison similar to that shown as the Visual Basic equivalent of GET.OBJECT(1).

GET.OBJECT(51)	Selection.Name
GET.OBJECT(52)	Selection.Left
GET.OBJECT(53)	Selection.Top
GET.OBJECT(54)	Selection.Width
GET.OBJECT(55)	Selection.Height
GET.OBJECT(56)	Selection.Enabled
GET.OBJECT(57)	Selection.Accelerator
GET.OBJECT(58)	Selection.DefaultButton
GET.OBJECT(59)	Selection.CancelButton
GET.OBJECT(60)	Selection.DismissButton
GET.OBJECT(61)	Selection.HelpButton
GET.OBJECT(62)	Selection.Value
GET.OBJECT(63)	Selection.Min
GET.OBJECT(64)	Selection.Max
GET.OBJECT(65)	Selection.SmallChange
GET.OBJECT(66)	Selection.LargeChange
GET.OBJECT(67)	Selection.InputType
GET.OBJECT(68)	Selection.MultiLine
GET.OBJECT(69)	Selection.DisplayVerticalScrollBar
GET.OBJECT(70)	Selection.LinkedObject
GET.OBJECT(71)	Selection.ListCount
GET.OBJECT(72)	Selection.List(Selection.ListIndex)
GET.OBJECT(73)	Selection.ListFillRange
GET.OBJECT(74)	Selection.DropDownLines
GET.OBJECT(75)	Selection.Display3DShading
GET.OBJECT(76)	Selection.PhoneticAccelerator
GET.OBJECT(77)	Selection.MultiSelect
GET.OBJECT(78)	Selection.Selected
GET.OBJECT(79)	Selection.AddIndent
GET.PIVOT.FIELD(type_num, pivot_field_name, pivot_table_name)	ActiveSheet.PivotTables(pivot_table_name). _ PivotFields(pivot_field_name).Property
Returns information about a pivot field in a PivotTable. If pivot_field_name and pivot_table_name are specified, use the appropriate Visual Basic method or property directly on an object returned by the PivotTables and PivotFields methods. If pivot_field_name and pivot_table_name are omitted, returns information about the pivot field that contains the active cell. For clarity, the remaining translations of GET.PIVOT.FIELD assume that pivot_field_name and pivot_table_name are omitted.

GET.PIVOT.FIELD(1)	Dim result Set pvtItems = ActiveCell.PivotField.PivotItems If pvtItems.Count = 0 Then result = CVErr(xlErrNA) Else ReDim result(1 To pvtItems.Count) x = 1 For Each i In pvtItems result(x) = i.Name x = x + 1 Next End If
Returns an array of pivot item names for the items that make up the field. Visual Basic has no direct equivalent; however. the PivotItems method returns a collection that can be iterated to examine the items. The example builds an equivalent array by iterating the collection.

Replace the PivotItems method with the VisibleItems, HiddenItems, ParentItems, and ChildItems methods to create equivalents for the GET.PIVOT.FIELD() type_num values 2, 3, 5, and 17, respectively.

GET.PIVOT.FIELD(2)
Returns an array of pivot item names for the visible items in the field. Visual Basic has no direct equivalent; however, the VisibleItems method returns a collection that can be iterated to examine the items. See the example for GET.PIVOT.FIELD(1), and use the VisibleItems method.

GET.PIVOT.FIELD(3)
Returns an array of pivot item names for the hidden items in the field. Visual Basic has no direct equivalent; however, the HiddenItems method returns a collection that can be iterated to examine the items. See the example for GET.PIVOT.FIELD(1), and use the HiddenItems method.

GET.PIVOT.FIELD(4)	ActiveCell.PivotField.Orientation
GET.PIVOT.FIELD(5)
Returns an array of pivot item names for all items in the field that are group parents. Visual Basic has no direct equivalent; however, the ParentItems method returns a collection that can be iterated to examine the items. See the example for GET.PIVOT.FIELD(1), and use the ParentItems method.

GET.PIVOT.FIELD(6)	ActiveCell.PivotField.Subtotals
No direct equivalent. Visual Basic returns an array of Boolean values instead of a bitstring value. Examine each entry of the array to determine whether a particular subtotal type is enabled.

GET.PIVOT.FIELD(7)	ActiveCell.PivotField.DataType
GET.PIVOT.FIELD(8)	With ActiveCell.PivotField result = Array(.Function, .Calculation, _ .BaseField, .BaseItem, .NumberFormat) End With
Returns an array of settings for the pivot field. Visual Basic allows examination of individual properties, but the example constructs an array equivalent to GET.PIVOT.FIELD(8).

GET.PIVOT.FIELD(9)	ActiveCell.PivotField.DataRange
GET.PIVOT.FIELD(10)	ActiveCell.PivotField.LabelRange
GET.PIVOT.FIELD(11)	ActiveCell.PivotField.TotalLevels
GET.PIVOT.FIELD(12)	ActiveCell.PivotField.GroupLevel
GET.PIVOT.FIELD(13)	ActiveCell.PivotField.ParentField
GET.PIVOT.FIELD(14)	ActiveCell.PivotField.ChildField
GET.PIVOT.FIELD(15)	ActiveCell.PivotField.SourceName
GET.PIVOT.FIELD(16)	ActiveCell.PivotField.Position
GET.PIVOT.FIELD(17)
Returns an array of pivot item names for all items in the field that are group children. Visual Basic has no direct equivalent; however, the ChildItems method returns a collection that can be iterated to examine the items. See the example for GET.PIVOT.FIELD(1), and use the ChildItems method.

GET.PIVOT.ITEM(type_num, pivot_item_name, pivot_field_name, pivot_table_name)	ActiveSheet.PivotTables(pivot_table_name). _ PivotFields(pivot_field_name). _ PivotItems(pivot_item_name).Property
Returns information about a pivot item in a PivotTable. If pivot_item_name, pivot_field_name, and pivot_table_name are specified, use the appropriate Visual Basic method or property directly on an object returned by the PivotTables, PivotFields, and PivotItems methods. If these arguments are omitted, returns information about the pivot item that contains the active cell. For clarity, the remaining translations of GET.PIVOT.ITEM assume that pivot_item_name, pivot_field_name, and pivot_table_name are omitted.

GET.PIVOT.ITEM(1)	ActiveCell.PivotItem.Position
GET.PIVOT.ITEM(2)	ActiveCell.PivotItem.LabelRange
GET.PIVOT.ITEM(3)	ActiveCell.PivotItem.DataRange
GET.PIVOT.ITEM(4)	Dim result Set chldItems = ActiveCell.PivotItem.ChildItems If chldItems.Count = 0 Then result = CVErr(xlErrNA) Else ReDim result(1 To chldItems.Count) x = 1 For Each i In chldItems result(x) = i.Name x = x + 1 Next End If
Returns an array of pivot item names for all child items of the current item if it's a parent item. Visual Basic has no direct equivalent; however, the ChildItems method returns a collection that can be iterated to examine the items. The example builds an equivalent array by iterating the collection.

GET.PIVOT.ITEM(5)	ActiveCell.PivotItem.ParentItem
GET.PIVOT.ITEM(6)	ActiveCell.PivotItem.ParentShowDetail
GET.PIVOT.ITEM(7)	ActiveCell.PivotItem.ShowDetail
GET.PIVOT.ITEM(8)	ActiveCell.PivotItem.Visible
GET.PIVOT.ITEM(9)	ActiveCell.PivotItem.SourceName
GET.PIVOT.TABLE(type_num, pivot_table_name)	ActiveSheet.PivotTables(pivot_table_name).Property
Returns information about a PivotTable. If pivot_table_name is specified, use the appropriate Visual Basic method or property directly on an object returned by the PivotTables method. If pivot_table_name is omitted, returns information about the PivotTable that contains the active cell. For clarity, the remaining translations of GET.PIVOT.TABLE assume that pivot_table_name is omitted.

GET.PIVOT.TABLE(1)	ActiveCell.PivotTable.RefreshName
GET.PIVOT.TABLE(2)	ActiveCell.PivotTable.RefreshDate
GET.PIVOT.TABLE(3)	Dim result Set flds = ActiveCell.PivotTable.PivotFields If flds.Count = 0 Then result = CVErr(xlErrNA) Else ReDim result(1 To flds.Count) x = 1 For Each f In flds result(x) = f.Name x = x + 1 Next End If
Returns an array of the pivot field names for all the fields in the PivotTable. Visual Basic has no direct equivalent; however, the PivotFields method returns a collection that can be iterated to examine the fields. The example builds an equivalent array by iterating the collection.

Replace the PivotFields method with the VisibleFields, HiddenFields, RowFields, ColumnFields, PageFields, and DataFields methods to create equivalents for the GET.PIVOT.TABLE() type_num values 5, 6, 7, 8, 9, and 10, respectively.

GET.PIVOT.TABLE(4)	ActiveCell.PivotTable.PivotFields.Count
GET.PIVOT.TABLE(5)
Returns an array of the pivot field names for all the visible fields in the PivotTable. Visual Basic has no direct equivalent; however, the VisibleFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the VisibleFields method.

GET.PIVOT.TABLE(6)
Returns an array of the pivot field names for all the hidden fields in the PivotTable. Visual Basic has no direct equivalent; however, the HiddenFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the HiddenFields method.

GET.PIVOT.TABLE(7)
Returns an array of the pivot field names for all the row fields in the PivotTable. Visual Basic has no direct equivalent; however, the RowFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the RowFields method.

GET.PIVOT.TABLE(8)
Returns an array of the pivot field names for all the column fields in the PivotTable. Visual Basic has no direct equivalent; however, the ColumnFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the ColumnFields method.

GET.PIVOT.TABLE(9)
Returns an array of the pivot field names for all the page fields in the PivotTable. Visual Basic has no direct equivalent; however, the PageFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the PageFields method.

GET.PIVOT.TABLE(10)
Returns an array of the pivot field names for all the data fields in the PivotTable. Visual Basic has no direct equivalent; however, the DataFields method returns a collection that can be iterated to examine the fields. See the example for GET.PIVOT.TABLE(3), and use the DataFields method.

GET.PIVOT.TABLE(11)	ActiveCell.PivotTable.TableRange1
GET.PIVOT.TABLE(12)	ActiveCell.PivotTable.TableRange2
GET.PIVOT.TABLE(13)	ActiveCell.PivotTable.RowRange
GET.PIVOT.TABLE(14)	ActiveCell.PivotTable.ColumnRange
GET.PIVOT.TABLE(15)	ActiveCell.PivotTable.DataLabelRange
GET.PIVOT.TABLE(16)	ActiveCell.PivotTable.PageRange
GET.PIVOT.TABLE(17)	ActiveCell.PivotTable.DataBodyRange
GET.PIVOT.TABLE(18)	ActiveCell.PivotTable.RowGrand
GET.PIVOT.TABLE(19)	ActiveCell.PivotTable.ColumnGrand
GET.PIVOT.TABLE(20)	ActiveCell.PivotTable.SaveData
GET.PIVOT.TABLE(21)	ActiveCell.PivotTable.HasAutoFormat
GET.PIVOT.TABLE(22)	ActiveCell.PivotTable.SourceData
GET.TOOL(1, bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Id
GET.TOOL(2, bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).OnAction
GET.TOOL(3, bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Pushed
GET.TOOL(4, bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Enabled
GET.TOOL(5, bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).BuiltInFace
GET.TOOL(6, bar_id, position)	ExecuteExcel4Macro("GET.TOOL(6, bar_id, position)")
Returns the help text associated with the toolbar button. Visual Basic has no direct equivalent. Instead, help text is associated with the macro assigned to the toolbar button.

GET.TOOL(7, bar_id, position)	ExecuteExcel4Macro("GET.TOOL(7, bar_id, position)")
Returns the ballon help associated with the toolbar button. Visual Basic has no equivalent.

GET.TOOLBAR(1, bar_id)	Dim result() ReDim result(1 To Toolbars(bar_id).ToolbarButtons.Count x = 1 For Each t In Toolbars(bar_id).ToolbarButtons result(x) = t.Id x = x + 1 Next
Returns an array of ID numbers corresponding to the buttons on the toolbar. Visual Basic has no direct equivalent; however, the ToolbarButtons collection can be iterated to examine toolbars. The example builds an equivalent array by iterating the collection.

GET.TOOLBAR(2, bar_id)	Toolbars(bar_id).Left
GET.TOOLBAR(3, bar_id)	Toolbars(bar_id).Top
GET.TOOLBAR(4, bar_id)	Toolbars(bar_id).Width
GET.TOOLBAR(5, bar_id)	Toolbars(bar_id).Height
GET.TOOLBAR(6, bar_id)	Toolbars(bar_id).Position
GET.TOOLBAR(7, bar_id)	Toolbars(bar_id).Visible
GET.TOOLBAR(8)	Dim result() ReDim result(1 To Toolbars.Count) x = 1 For Each t In Toolbars result(x) = t.Name x = x + 1 Next
Returns an array of the toolbar names for all the toolbars, whether visible and hidden. Visual Basic has no direct equivalent; however, the Toolbars collection can be iterated to examine toolbars. The example builds an equivalent array by iterating the collection.

GET.TOOLBAR(9)	Dim result() ReDim result(1 To Toolbars.Count) x = 1 For Each t In Toolbars If t.Visible Then result(x) = t.Name x = x + 1 End If Next ReDim result(1 To (x - 1))
Returns an array of the toolbar names for all the visible toolbars. Visual Basic has no direct equivalent; however, the Toolbars collection can be iterated to examine toolbars. The example builds an equivalent array by iterating the collection and filtering for visible toolbars.

GET.TOOLBAR(10, bar_id)	ExecuteExcel4Macro("GET.TOOLBAR(10, bar_id)")
Returns a result indicating whether a toolbar is visible in full-screen mode. Visual Basic has no direct equivalent.

GET.WINDOW(type_num, window_text)	Windows(window_text).Property
Returns information about a window. If window_text is specified, use the appropriate Visual Basic method or property directly on an object returned by the Windows method. If window_text is omitted, returns information about the active window. For clarity, the remaining translations of GET.WINDOW assume that window_text is omitted.

GET.WINDOW(1)	Set containingBook = ActiveWindow.ActiveSheet.Parent If containingBook.Sheets.Count = 1 Then ' Get bookname, strip off extension (if any) bookName = containingBook.Name For i = Len(bookName) To 1 Step -1 If Mid(bookName, i, 1) = "." Then bookName = Mid(bookName, 1, i - 1) Exit For End If Next x = StrComp(bookName, _ ActiveWindow.ActiveSheet.Name, 1) If x <> 0 Then Goto BuildLongName result = containingBook.Name Else BuildLongName: result = "[" & containingBook.Name & _ "]" & ActiveWindow.ActiveSheet.Name End If
Returns the name of the workbook and sheet in the window. The example constructs an exact equivalent of GET.WINDOW(1), which has special rules to provide backward compatability with Microsoft Excel version 4.0. In Visual Basic, it's not necessary to construct such an equivalent, because the Worksheet and Workbook objects are used instead of a text name.

GET.WINDOW(2)	ActiveWindow.WindowNumber
GET.WINDOW(3)	ActiveWindow.Left
GET.WINDOW(4)	ActiveWindow.Top
GET.WINDOW(5)	ActiveWindow.Width
GET.WINDOW(6)	ActiveWindow.Height
GET.WINDOW(7)	ActiveWindow.Visible
GET.WINDOW(8)	ActiveWindow.DisplayFormulas
GET.WINDOW(9)	ActiveWindow.DisplayGridlines
GET.WINDOW(10)	ActiveWindow.DisplayHeadings
GET.WINDOW(11)	ActiveWindow.DisplayZeros
GET.WINDOW(12)	ActiveWindow.GridlineColorIndex
GET.WINDOW(13)	ActiveWindow.Panes(1).ScrollColumn
Returns an array that contains the leftmost column numbers for all panes. Visual Basic has no direct equivalent. Use the Panes collection to examine the properties of a particular pane. If required, construct an array of result values by iterating all panes in the collection.

GET.WINDOW(14)	ActiveWindow.Panes(1).ScrollRow
Returns an array that contains the topmost row numbers for all panes. Visual Basic has no direct equivalent. Use the Panes collection to examine the properties of a particular pane. If required, construct an array of result values by iterating all panes in the collection.

GET.WINDOW(15)	ExecuteExcel4Macro("INDEX(GET.WINDOW(15),,pane_num)")
No direct equivalent. The VisibleRange property returns a range that contains all the visible cells (even if the cell is only partially visible). You can convert this range to the fractional width values returned by GET.WINDOW(15), or you can use the ExecuteExcel4Macro method.

GET.WINDOW(16)	ExecuteExcel4Macro("INDEX(GET.WINDOW(16),,pane_num)")
No direct equivalent. The VisibleRange property returns a range that contains all the visible cells (even if the cell is only partially visible). You can convert this range to the fractional height values returned by GET.WINDOW(16), or you can use the ExecuteExcel4Macro method.

GET.WINDOW(17)	result = ActiveWindow.ActivePane.Index If ActiveWindow.Panes.Count = 2 Then If ActiveWindow.SplitVertical <> 0 Then If result = 2 Then result = 3 End If End If
Returns the index of the pane. In Visual Basic, the panes are renumbered depending on the split configuration, so conversion is necessary to return an exact equivalent.

GET.WINDOW(18)	ActiveWindow.SplitVertical <> 0
GET.WINDOW(19)	ActiveWindow.SplitHorizontal <> 0
GET.WINDOW(20)	ActiveWindow.WindowState = xlMaximized
GET.WINDOW(22)	ActiveWindow.DisplayOutline
GET.WINDOW(23)	ActiveWindow.WindowState
GET.WINDOW(24)	ActiveWindow.FreezePanes
GET.WINDOW(25)	ActiveWindow.Zoom
GET.WINDOW(26)	ActiveWindow.DisplayHorizontalScrollBar
GET.WINDOW(27)	ActiveWindow.DisplayVerticalScrollBar
GET.WINDOW(28)	ActiveWindow.TabRatio
GET.WINDOW(29)	ActiveWindow.DisplayWorkbookTabs
GET.WINDOW(30)	"[" & ActiveWindow.ActiveSheet.Parent.Name & _ "]" & ActiveWindow.ActiveSheet.Name
GET.WINDOW(31)	ActiveWindow.ActiveSheet.Parent.Name
GET.WORKBOOK(type_num, name_text)	Workbooks(name_text).Property
Returns information about a workbook. If name_text is specified, use the appropriate Visual Basic method or property directly on a workbook object returned by the Workbooks method. If name_text is omitted, returns information about the active workbook. For clarity, the remaining translations of GET.WORKBOOK assume that name_text is omitted.

GET.WORKBOOK(1)	Dim result() ReDim result(1 To ActiveWorkbook.Sheets.Count) bkName = "[" & ActiveWorkbook.Name & "]" x = 1 For Each s In ActiveWorkbook.Sheets result(x) = bkName & s.Name x = x + 1 Next
Returns an array of the sheet names for all the sheets in the workbook. Visual Basic has no direct equivalent; however, the Sheets collection can be iterated to examine sheets. The example builds an equivalent array by iterating the collection.

GET.WORKBOOK(2)	CVErr(xlErrNA)
In Microsoft Excel version 5.0 or later, this function always returns the #N/A error value.

GET.WORKBOOK(3)	Dim result() ReDim result(1 To ActiveWindow.SelectedSheets.Count) bkName = "[" & ActiveWorkbook.Name & "]" x = 1 For Each s In ActiveWindow.SelectedSheets result(x) = bkName & s.Name x = x + 1 Next
Returns an array of the sheet names for the selected sheets in the workbook. Visual Basic has no direct equivalent; however, the SelectedSheets method returns a collection that can be iterated to examine the selected sheets. The example builds an equivalent array by iterating the collection.

GET.WORKBOOK(4)	ActiveWorkbook.Sheets.Count
GET.WORKBOOK(5)	ActiveWorkbook.HasRoutingSlip
GET.WORKBOOK(6)	ActiveWorkbook.RoutingSlip.Recipients
GET.WORKBOOK(7)	ActiveWorkbook.RoutingSlip.Subject
GET.WORKBOOK(8)	ActiveWorkbook.RoutingSlip.Message
GET.WORKBOOK(9)	ActiveWorkbook.RoutingSlip.Delivery
GET.WORKBOOK(10)	ActiveWorkbook.RoutingSlip.ReturnWhenDone
GET.WORKBOOK(11)	ActiveWorkbook.Routed
GET.WORKBOOK(12)	ActiveWorkbook.RoutingSlip.TrackStatus
GET.WORKBOOK(13)	ActiveWorkbook.RoutingSlip.Status
GET.WORKBOOK(14)	ActiveWorkbook.ProtectStructure
GET.WORKBOOK(15)	ActiveWorkbook.ProtectWindows
GET.WORKBOOK(16)	ActiveWorkbook.Name
GET.WORKBOOK(17)	ActiveWorkbook.ReadOnly
GET.WORKBOOK(18)	ActiveWorkbook.WriteReserved
GET.WORKBOOK(19)	ActiveWorkbook.WriteReservedBy
GET.WORKBOOK(20)	ActiveWorkbook.FileFormat
GET.WORKBOOK(21)	ActiveWorkbook.CreateBackup
GET.WORKBOOK(22)	ActiveWorkbook.SaveLinkValues
GET.WORKBOOK(23)	ActiveWorkbook.HasMailer
GET.WORKBOOK(24)	Not ActiveWorkbook.Saved
GET.WORKBOOK(25)	ActiveWorkbook.Mailer.ToRecipients
GET.WORKBOOK(26)	ActiveWorkbook.Mailer.CCRecipients
GET.WORKBOOK(27)	ActiveWorkbook.Mailer.BCCRecipients
GET.WORKBOOK(28)	ActiveWorkbook.Mailer.Subject
GET.WORKBOOK(29)	ActiveWorkbook.Mailer.Enclosures
GET.WORKBOOK(30)	ActiveWorkbook.Mailer.Received
GET.WORKBOOK(31)	ActiveWorkbook.Mailer.SendDateTime
GET.WORKBOOK(32)	ActiveWorkbook.Mailer.Sender
GET.WORKBOOK(33)	ActiveWorkbook.Title
GET.WORKBOOK(34)	ActiveWorkbook.Subject
GET.WORKBOOK(35)	ActiveWorkbook.Author
GET.WORKBOOK(36)	ActiveWorkbook.Keywords
GET.WORKBOOK(37)	ActiveWorkbook.Comments
GET.WORKBOOK(38)	ActiveWorkbook.ActiveSheet.Name
GET.WORKSPACE(1)	Application.OperatingSystem
GET.WORKSPACE2)	Application.Version
GET.WORKSPACE(3)	Application.FixedDecimal
GET.WORKSPACE(4)	Application.ReferenceStyle = xlR1C1
GET.WORKSPACE(5)	Application.DisplayScrollBars
GET.WORKSPACE(6)	Application.DisplayStatusBar
GET.WORKSPACE(7)	Application.DisplayFormulaBar
GET.WORKSPACE(8)	Not Application.IgnoreRemoteRequests
GET.WORKSPACE(9)	Application.TransitionMenuKey
GET.WORKSPACE(10)	Application.DataEntryMode Application.CutCopyMode
Returns a number indicating the current user mode. Use either of the listed properties. Microsoft Excel version 5.0 or later has no equivalent for Data Find mode.

GET.WORKSPACE(11)	Application.Left
GET.WORKSPACE(12)	Application.Top
GET.WORKSPACE(13)	Application.UsableWidth
GET.WORKSPACE(14)	Application.UsableHeight
GET.WORKSPACE(15)	Application.WindowState
GET.WORKSPACE(16)	Application.MemoryFree
GET.WORKSPACE(17)	Application.MemoryTotal
GET.WORKSPACE(18)	Application.MathCoprocessorAvailable
GET.WORKSPACE(19)	Application.MouseAvailable
GET.WORKSPACE(20)	Dim result If ActiveWindow.SelectedSheets.Count = 1 Then result = CVErr(xlErrNA) Else ReDim result(1 To ActiveWindow.SelectedSheets.Count) bkName = "[" & ActiveWorkbook.Name & "]" x = 1 For Each s In ActiveWindow.SelectedSheets result(x) = bkName & s.Name x = x + 1 Next End If
Returns an array that contains the sheet names of the group edit. In Microsoft Excel version 5.0 or later, you create groups by selecting multiple sheet tabs. The example constructs an array using the collection of sheets returned by the SelectedSheets method.

GET.WORKSPACE(21)	Toolbars("Standard").Visible
GET.WORKSPACE(22)	Application.DDEAppReturnCode
GET.WORKSPACE(type_num)	Application.StartupPath
GET.WORKSPACE(24)	Application.AltStartupPath
GET.WORKSPACE(25)	Application.RecordRelative
GET.WORKSPACE(26)	Application.UserName
GET.WORKSPACE(27)	Application.OrganizationName
GET.WORKSPACE(28)	Application.TransitionMenuKeyAction
GET.WORKSPACE(29)	Application.TransitionNavigKeys
GET.WORKSPACE(30)	ExecuteExcel4Macro("INDEX(GET.WORKSPACE(30),,num)")
No direct equivalent. Because the ExecuteExcel4Macro method cannot return an array, use the INDEX function to retrieve the settings one at a time.

GET.WORKSPACE(31)
No equivalent in Visual Basic.

GET.WORKSPACE(32)	Application.Path
GET.WORKSPACE(33)
No direct equivalent.

GET.WORKSPACE(34)
No direct equivalent.

GET.WORKSPACE(35)
No equivalent in Visual Basic.

GET.WORKSPACE(36)	Application.CellDragAndDrop
GET.WORKSPACE(37)	Application.International
GET.WORKSPACE(38)	Application.DisplayAlerts
No direct equivalent. The DisplayAlerts property indicates whether alerts are turned on or off, but it doesn't indicate whether error trapping is completely disabled. The status of Visual Basic error trapping, as set by the On Error statement, is not available.

GET.WORKSPACE(39)
No equivalent in Visual Basic. The location of the currently active error handler set by the On Error statement is not available.

GET.WORKSPACE(40)	Application.ScreenUpdating
GET.WORKSPACE(41)	Application.PreviousSelections
GET.WORKSPACE(42)	Application.CanPlaySounds
GET.WORKSPACE(43)	Application.CanRecordSounds
GET.WORKSPACE(44)	Application.RegisteredFunctions
Returns an array of information about DLL or code resource functions registered for use by worksheets and macro sheets. Note that these functions aren't directly callable by Visual Basic and aren't related to the DLL and code resources declared within Visual Basic by the Declare Function and Declare Sub statements.

GET.WORKSPACE(45)	Application.WindowsForPens
GET.WORKSPACE(46)	Application.MoveAfterReturn
GET.WORKSPACE(48)	Application.LibraryPath
GET.WORKSPACE(49)	Application.MailSession
GET.WORKSPACE(50)	Application.DisplayFullScreen
GET.WORKSPACE(51)	ExecuteExcel4Macro("GET.WORKSPACE(51)")
No direct equivalent.

GET.WORKSPACE(52)	ExecuteExcel4Macro("GET.WORKSPACE(51)")
No direct equivalent.

GET.WORKSPACE(53)	Application.ActiveDialog.Name
GET.WORKSPACE(54)	Application.EditDirectlyInCell
GET.WORKSPACE(55)	Application.AlertBeforeOverwriting
GET.WORKSPACE(56)	Application.StandardFont
GET.WORKSPACE(57)	Application.StandardFontSize
GET.WORKSPACE(58)	Application.DisplayRecentFiles
GET.WORKSPACE(59)	Application.DisplayExcel4Menus
GET.WORKSPACE(60)	Application.EnableTipWizard
GET.WORKSPACE(61)	Application.CustomListCount
GET.WORKSPACE(62)	Application.FileConverters
GET.WORKSPACE(63)	Application.MailSystem
GET.WORKSPACE(64)	Application.AskToUpdateLinks
GET.WORKSPACE(65)	Application.CopyObjectsWithCells
GET.WORKSPACE(66)	Application.SheetsInNewWorkbook
GET.WORKSPACE(67)	Application.DefaultFilePath
GET.WORKSPACE(68)	Application.ShowToolTips
GET.WORKSPACE(69)	Application.LargeButtons
GET.WORKSPACE(70)	Application.PromptForSummaryInfo
GET.WORKSPACE(71)	ExecuteExcel4Macro("GET.WORKSPACE(71)")
GET.WORKSPACE(72)	Application.ColorButtons
GOAL.SEEK(target_cell, target_value, variable_cell)	Range(target_cell).GoalSeek goal := target_value, _ changingCell := variable_cell
GOTO(reference)	GoTo TargetLabel ' code that is skipped here TargetLabel: ' execution resumes here, following the label
Use the Visual Basic GoTo statement to branch unconditionally. Unlike the GOTO() function, Visual Basic requires hard-coded label values that cannot be changed at run time.

GRIDLINES(x_major, x_minor, y_major, y_minor)	With ActiveChart.Axes(xlCategory) .HasMajorGridlines = x_major .HasMinorGridlines = x_minor End With With ActiveChart.Axes(xlValue) .HasMajorGridlines = y_major .HasMinorGridlines = y_minor End With
Controls gridline settings for 2D charts.

GRIDLINES(x_major, x_minor, y_major, y_minor, z_major, z_minor, 2D_effect)	With ActiveChart.Axes(xlCategory) .HasMajorGridlines = x_major .HasMinorGridlines = x_minor End With With ActiveChart.Axes(xlSeries) .HasMajorGridlines = y_major .HasMinorGridlines = y_minor End With With ActiveChart.Axes(xlValue) .HasMajorGridlines = z_major .HasMinorGridlines = z_minor End With ActiveChart.WallsAndGridlines2D = 2D_effect
Controls gridline settings for 3D charts.

GROUP( )	Selection.Group.Select
Groups the selected drawing objects.


Visual Basic Equivalents H through K
Visual Basic Equivalents for Macro Functions and Commands

H

HALT(cancel_close)	End
The cancel_close argument has no equivalent.

HELP(help_ref)	sepOffset = InStr(help_ref, "!") helpFile = Left(help_ref, sepOffset - 1) helpContextID = CInt(Right(help_ref, Len(help_ref) - sepOffset)) Application.Help helpFile, helpContextID
In the Microsoft Excel 4.0 macro language, the Help reference is specified as a string containing the help filename followed by the help context number (for example "PROJECT.HLP!255"). In Visual Basic, the Help file and the Help context are specified separately instead of in a single string. The example divides the help_ref string argument into its string and numeric components.

HIDE( )	ActiveWindow.Visible = False
HIDE.DIALOG(cancel_logical)	ActiveDialog.Hide cancel := cancel_logical
HIDE.OBJECT(, hide_logical)	Selection.Visible = hide_logical
Hides or unhides the selected drawing object.

HIDE.OBJECT("Oval 1", hide_logical	ActiveSheet.DrawingObjects("Oval 1").Visible = hide_logical
Hides or unhides a specific drawing object that's not selected. Use the ActiveChart property instead of the ActiveSheet property if the drawing object is in a chart.

HIDE.OBJECT("Oval 1, Rectangle 2", hide_logical)	ActiveSheet.DrawingObjects( _ Array("Oval 1", "Rectangle 2")).Visible = hide_logical
Hides or unhides a group of specific drawing objects that aren't selected. Use the ActiveChart property instead of the ActiveSheet property if the drawing objects are in a chart.

HLINE(num_columns)	ActiveWindow.SmallScroll toRight := num_columns
HPAGE(num_windows)	ActiveWindow.LargeScroll toRight := num_windows
HSCROLL(position, TRUE)	ActiveWindow.ScrollColumn = position
Scrolls horizontally to a specific column number.

HSCROLL(position, FALSE)	ActiveWindow.ScrollColumn = position * 256
Scrolls horizontally to a fractional position. In Visual Basic, you can scroll to specific columns only. The example converts a fraction to an absolute column number.

I

IF(logical_test)	If logical_test Then ' code for True condition Else ' code for False condition End If
Evaluates the logical_test expression and, based on the results, runs code between the IF function and the ELSE, ELSE.IF, or END.IF functions. The Visual Basic example illustrates the complete If statement syntax.

IF(logical_test, value_if_true, value_if_false)	If logical_test Then result = value_if_true Else result = value_if_false End If
Evaluates the logical_test expression and, depending on the test value, returns the value of either the true_value expression or the false_value expression. Visual Basic has no direct equivalent; use a temporary variable instead.

INITIATE(app_text, topic_text)	Application.DDEInitiate app := app_text, topic := topic_text
INPUT(message_text, type_num, title_text, default, x_pos, y_pos, help_ref)	Application.InputBox prompt := message_text, title := title_text, _ default := default, left := x_pos, top := y_pos, _ helpFile := help_ref, helpContextID := help_file, _ type := type_num
Opens a dialog box containing an edit field for user input. The help_ref argument is split into a separate Help filename and Help context number in Visual Basic. See the HELP function for an example of how to convert the help_ref argument into these two components. The InputBox function in the Visual Basic run-time library provides similar functionality but it doesn't support the type_num argument. If you plan to run your code in other Visual Basic environments, use the InputBox function.

INSERT(1)	Selection.Insert shift := xlToRight
INSERT(2)	Selection.Insert shift := xlDown
INSERT(3)	Selection.EntireRow.Insert
INSERT(4)	Selection.EntireColumn.Insert
INSERT.OBJECT(object_class, file_name, link_logical, display_icon_logical, icon_file, icon_number, icon_label)	ActiveSheet.OLEObjects.Add classType := object_class, _ fileName := file_name, link := link_logical, _ displayAsIcon := display_icon_logical, _ iconFileName := icon_file, iconIndex := icon_number, _ iconLabel := icon_label
INSERT.PICTURE(file_name, filter_number)	ActiveSheet.Pictures.Insert filename := file_name, _ converter := filter_number
INSERT.TITLE(chart, y_primary, x_primary, y_secondary, x_secondary)	With ActiveChart .HasTitle = chart .Axes(xlCategory, xlPrimary).HasTitle = x_primary .Axes(xlCategory, xlSecondary).HasTitle = x_secondary .Axes(xlValue, xlPrimary).HasTitle = y_primary .Axes(xlValue, xlSecondary).HasTitle = y_secondary End With
Attaches text to a 2-D chart.

INSERT.TITLE(chart, z_primary, x_primary, y_primary)	With ActiveChart .HasTitle = chart .Axes(xlValue).HasTitle = chart, z_primary, x_primary .Axes(xlCategory).HasTitle = x_primary .Axes(xlSeries).HasTitle = x_primary, y_primary) End With
Attaches text to a 3-D chart.

J

JUSTIFY()	Selection.Justify
K


Visual Basic Equivalents L through N
Visual Basic Equivalents for Macro Functions and Commands

L

LABEL.PROPERTIES(accel_text, accel2_text, 3d_shading)	With Selection .Accelerator = accel_text .PhoneticAccelerator = accel2_text .Display3DShading = 3d_shading End With
LAST.ERROR( )	Erl
No direct equivalent. Use the Erl function to return the line number of the Visual Basic expression that caused the last Visual Basic error.

LEGEND(logical)	ActiveChart.HasLegend = logical
LINE.PRINT( )	ExecuteExcel4Macro("LINE.PRINT(...)")
No direct equivalent. Use either the ExecuteExcel4Macro method or a combination of the Visual Basic Write and Print statements to create output files.

LINK.COMBO(link_logical)	Selection.LinkCombo link := link_logical
LINK.FORMAT( )	Selection.TickLabels.NumberFormatLinked = True
Use this syntax if axis tick labels are selected.

LINK.FORMAT( )	Selection.NumberFormatLinked = True
Use this syntax if objects other than axis tick labels are selected.

LINKS(document_text, type_num)	Workbooks(document_text).LinkSources type := type_num
Use the ActiveWorkbook property instead of Workbooks(document_text) if the document_text argument is omitted.

LIST.NAMES( )	Selection.ListNames
LISTBOX.PROPERTIES(range, link, drop_size, multi_select, 3d_shading)	With Selection .ListFillRange = range .LinkedCell = link .DropDownLines = drop_size .MultiSelect = multi_select .Display3DShading = 3d_shading End With
M

MAIL.ADD.MAILER( )	ActiveWorkbook.HasMailer = True
MAIL.DELETE.MAILER( )	ActiveWorkbook.HasMailer = False
MAIL.EDIT.MAILER(to_recipients, cc_recipients, bcc_recipients, subject, enclosures, which_address)	With ActiveWorkbook.Mailer .ToRecipients = to_recipients .CCRecipients = bcc_recipients .BCCRecipients = bcc_recipients .Subject = subject .Enclosures = enclosures End With
The which_address argument has no direct equivalent in Visual Basic.

MAIL.FORWARD( )	ActiveWorkbook.ForwardMailer
MAIL.LOGOFF( )	Application.MailLogoff
MAIL.LOGON(name_text, password_text, download_logical)	Application.MailLogon name := name_text, _ password := password_text, _ downloadNewMail := download_logical
MAIL.NEXT.LETTER( )	Application.NextLetter
MAIL.REPLY( )	ActiveWorkbook.Reply
MAIL.REPLY.ALL( )	ActiveWorkbook.ReplyAll
MAIN.CHART(type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle)	With ActiveChart .Type = type_num .SubType = 100 End With With ActiveChart.ChartGroups(1) .VaryByCategories = vary .Overlap = overlap% .HasDropLines = drop .HasHiLoLines = hilo .FirstSliceAngle = angle End With
This function is used only for backward compatability with Microsoft Excel version 2.2 or earlier. Some arguments don't apply to all chart types, and the stack, overlap, and cluster arguments have no direct equivalent in Microsoft Excel version 5.0 or later.

MAIN.CHART.TYPE(type_num)	ActiveChart.Type = type_num
MENU.EDITOR()	Application.Dialogs(xlDialogMenuEditor).Show
MERGE.STYLES(document_text)	ActiveWorkbook.Styles.Merge _ workbook := Workbooks(document_text)
MESSAGE(TRUE, text)	Application.StatusBar = text
Displays text in the status bar.

MESSAGE(FALSE)	Application.StatusBar = False
Restores the status bar to its default message display.

MOVE.TOOL(from_bar_id, from_bar_position, to_bar_id, to_bar_position, TRUE)	With Toolbars(from_bar_id).ToolbarButtons(from_bar_position) .Copy toolbar := Toolbars(to_bar_id), _ before := to_bar_position End With
Copies a button from one toolbar to another.

MOVE.TOOL(from_bar_id, from_bar_position, to_bar_id, to_bar_position, FALSE)	With Toolbars(from_bar_id).ToolbarButtons(from_bar_position) .Move toolbar := Toolbars(to_bar_id), _ before := to_bar_position End With
Moves a button from one toolbar to another.

MOVE.TOOL(from_bar_id, from_bar_position, , , , width)	With Toolbars(from_bar_id).ToolbarButtons(from_bar_position) .Width = width End With
Resizes a toolbar button that displays a drop-down list.

N

NAMES(document_text, 3)	For Each n In ActiveWorkbook.Names MsgBox n.Name Next
Returns an array of all the range names. In Visual Basic, the Names collection provides direct access to Name objects and doesn't require you to use text names. The example displays the name of each range name in a message box. If 1 or 2 is specified for type_num, examine the Visible property of the Name object to determine whether the name should be included.

NAMES(document_text, 2, match_text)	Dim result() As String numNames = 0 For Each n In ActiveWorkbook.Names If n.Visible = False And n.Name Like match_text Then numNames = numNames + 1 ReDim Preserve result(1 To numNames) result(numNames) = n.Name End If Next
Returns an array of range names with titles that match a given pattern, with additional filtering for hidden names only. The example constructs an array of range names that match the pattern and are hidden. Note the use of the Names collection in a For Each...Next statement.

NEW(type_num, xy_series, add_logical)	Workbooks.Add template := type_num
Adds a new workbook based on the template type_num if type_num is text. If type_num is omitted, a default workbook is created. The xy_series and add_logical arguments have no direct equivalent in Visual Basic.

NEW(1)	Workbooks.Add template := xlWorksheet
Adds a new workbook that contains a single worksheet.

NEW(2)	Workbooks.Add template := xlChart
Adds a new workbook that contains a single chart based on the current selection.

NEW(3)	Workbooks.Add template := xlExcel4MacroSheet
Adds a new workbook that contains a single Microsoft Excel 4.0 macro sheet.

NEW(4)	Workbooks.Add template := xlExcel4IntlMacroSheet
Adds a new workbook that contains a single Microsoft Excel 4.0 international macro sheet.

NEW(5)	Workbooks.Add
Adds a new workbook that contains the default number of worksheets or is based on the default workbook template.

NEW.WINDOW( )	ActiveWindow.NewWindow
NEXT( )	For x = 1 To 100 ' loop body Next
Ends a loop. The example illustrates the full Visual Basic syntax.

NOTE(, cell_ref)	Range(cell_ref).ClearNotes
Deletes a cell note.

NOTE(add_text, cell_ref, start_char, num_chars)	Range(cell_ref).NoteText text := add_text, _ start := start_char, length := num_chars
Adds text to a cell note.


Visual Basic Equivalents O through Q
Visual Basic Equivalents for Macro Functions and Commands

O

OBJECT.PROPERTIES(placement_type, print_object)	With Selection .Placement = placement_type .PrintObject = print_object End With
OBJECT.PROTECTION(locked, lock_text)	With Selection .Locked = locked .LockedText = lock_text End With
ON.DATA(document_text, macro_text)	ActiveWorkbook.SetLinkOnData name := document_text, _ procedure := macro_text
ON.DOUBLECLICK(sheet_text, macro_text)	Sheets(sheet_text).OnDoubleClick = macro_text
Runs the specified macro when a particular sheet is double-clicked.

ON.DOUBLECLICK(, macro_text)	Application.OnDoubleClick = macro_text
Runs the specified macro when a double-click occurs on any sheet that doesn't already have a double-click macro defined.

ON.ENTRY(sheet_text, macro_text)	Sheets(sheet_text).OnEntry = macro_text
Runs the specified macro whenever data is entered in a cell on a particular sheet.

ON.ENTRY(, macro_text)	Application.OnEntry = macro_text
Runs the specified macro whenever data is entered in a cell on any sheet that doesn't already have a data-entry macro defined.

ON.KEY(key_text, macro_text)	Application.OnKey key := key_text, procedure := macro_text
ON.RECALC(sheet_text, macro_text)	Sheets(sheet_text).OnCalculate = macro_text
Runs the specified macro whenever a particular sheet is calculated.

ON.RECALC(, macro_text	Application.OnCalculate = macro_text
Runs the specified macro whenever calculation occurs for any sheet that doesn't already have a calculation macro defined.

ON.SHEET("[BOOK1]Sheet1", macro_text, TRUE)	Workbooks("BOOK1").Sheets("Sheet1").OnSheetActivate = _ macro_text
Runs the specified macro whenever a particular sheet in a particular workbook is activated. If the last parameter is FALSE, use the OnSheetDeactivate property instead of OnSheetActivate.

ON.SHEET("[BOOK1]", macro_text, TRUE)	Workbooks("BOOK1").OnSheetActivate = macro_text
Runs the specified macro whenever any sheet in a particular workbook is activated. If the last parameter is FALSE, use the OnSheetDeactivate property instead of OnSheetActivate.

ON.SHEET(sheet_text, macro_text, TRUE)	Application.OnSheetActivate = macro_text
Runs the specified macro whenever any sheet in any workbook is activated. If the last parameter is FALSE, use the OnSheetDeactivate property instead of OnSheetActivate.

ON.TIME(time, macro_text, tolerance, insert_logical)	Application.OnTime earliestTime := insert_logical, _ procedure := macro_text, latestTime := tolerance, _ schedule := insert_logical
ON.WINDOW(window_text, macro_text)	Windows(window_text).OnWindow = macro_text
Runs the specified macro whenever a particular window is activated.

ON.WINDOW(, macro_text)	Application.OnWindow = macro_text
Runs the specified macro whenever any window that doesn't already have an activation macro is activated.

OPEN(file_text, update_links, read_only, format, prot_pwd, write_res_pwd, ignore_rorec, file_origin, custom_delimit, , editable, , notify_logical, converter)	Workbooks.Open filename := file_text, _ updateLinks := update_links, readOnly := read_only, _ format := format, password := prot_pwd, _ writeResPassword := write_res_pwd, _ ignoreReadOnlyRecommended := ignore_rorec, _ origin := file_origin, delimiter := custom_delimit, _ editable := editable, notify := notify_logical, _ converter := converter
Opens a file. The add_logical parameter has no equivalent in Microsoft Excel version 5.0 or later.

OPEN?(file_text)	Application.Dialogs(xlDialogOpen).Show file_text
Displays the Open dialog box (File menu) with a default filename, and opens the selected file. In Visual Basic, use the Dialogs collection with the appropriate dialog constant. Arguments passed to the Show method are used as the default values in the dialog box. The Show method arguments are identical to those used by the equivalent Microsoft Excel 4.0 macro command. Arguments must be specified by position.

OPEN(file_text, , , , , write_res_pwd, , , , , , 2, notify_logical)	Workbooks(file_text).ChangeFileAccess _  mode := xlReadWrite, notify := notify_logical, _ writePassword := write_res_pwd
Changes a workbook's access status to read-write.

OPEN(file_text, , , , , , , , , , , 3)	Workbooks(file_text).ChangeFileAccess mode := xlReadOnly
Changes a workbook's access status to read-only.

OPEN(file_text, , TRUE, , , , , , , , , 1)	Workbooks(file_text).UpdateFromFile
Updates a workbook with the most recently saved disk copy, possibly discarding changes made in memory.

OPEN.DIALOG(file_filter, button_text, title, filter_index)	Application.GetOpenFilename fileFilter := file_filter, _ filterIndex := filter_index, title := title, _ buttonText := button_text
OPEN.LINKS(document_text1, document_text2, ..., read_only, type_of_link)	ActiveWorkbook.OpenLinks _ name := Array(document_text1, document_text2), _ readOnly = read_only, type := type_of_link
Opens the specified supporting documents. If multiple documents are specified, Visual Basic requires an array for the name argument. The example uses the Array function to construct an array.

OPEN.MAIL(subject, comments)	ExecuteExcel4Macro("comments.comments(subject, comments)")
No direct equivalent.

OPEN.TEXT(file_name, file_origin, start_row, file_type, text_qualifier, consecutive_delim, tab, semicolon, comma, space, other, other_char, {field_info; field_info2;...}	Workbooks.OpenText filename := file_name, _ origin := file_origin, startRow := start_row, _ dataType := file_type, textQualifier := text_qualifier, _ consecutiveDelimiter := consecutive_delim, _ tab := tab, semicolon := semicolon, comma := comma, _ space := space, other := other_char, _ otherChar := other_char, fieldInfo := field_info2
OPTIONS.CALCULATION(type_num, iter, max_num, max_change, update, precision,  date_1904, calc_save, save_values)	With Application .Calculation = type_num .Iteration = iter .MaxIterations = max_num .MaxChange = max_change .CalculateBeforeSave = calc_save End With With ActiveWorkbook .UpdateRemoteReferences = update .PrecisionAsDisplayed = precision .Date1904 = date_1904 .SaveLinkValues = save_values End With
OPTIONS.CHART(display_blanks, plot_visible, size_with_window)	With ActiveChart .DisplayBlanksAs = display_blanks .PlotVisibleOnly = plot_visible .SizeWithWindow =  size_with_window End With
OPTIONS.EDIT(incell_edit, drag_drop, alert, entermove, fixed, decimals,copy_objects, update_links)	With Application .EditDirectlyInCell = incell_edit .CellDragAndDrop = drag_drop .AlertBeforeOverwriting = alert .MoveAfterReturn = entermove .FixedDecimal = fixed .FixedDecimalPlaces = decimals .CopyObjectsWithCells = copy_objects .AskToUpdateLinks = update_links End With
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)	With Application .ReferenceStyle = R1C1_mode .IgnoreRemoteRequests = dde_on .PromptForSummaryInfo = sum_info .DisplayRecentFiles = recent_files .DisplayExcel4Menus = old_menus .UserName = user_info .StandardFont = font_name .StandardFontSize = font_size .DefaultFilePath = default_location .AltStartupPath = alternate_location .SheetsInNewWorkbook = sheet_num .CommandUnderlines = enable_under End With Application.ResetTipWizard
If the tips argument is FALSE or omitted, don't include the ResetTipWizard method.

OPTIONS.LISTS.ADD(string_array)	Application.AddCustomList listArray := string_array
Adds the contents of an array as a custom list . In Visual Basic, use the Array function to easily create arrays of string values.

OPTIONS.LISTS.ADD(import_ref, by_row)	Application.AddCustomList listArray := import_ref, _ byRow := by_row
Adds the contents of a cell range as a custom list.

OPTIONS.LISTS.DELETE(list_num)	Application.DeleteCustomList listNum = list_num
OPTIONS.LISTS.GET(list_num)	Application.GetCustomListContents(listNum := list_num)
OPTIONS.TRANSITION(menu_key, menu_key_action, nav_keys, trans_eval, trans_entry )	With Application .TransitionMenuKey = menu_key_action .TransitionMenuKeyAction = menu_key_action .TransitionNavigKeys = nav_keys End With With ActiveSheet .TransitionExpEval = trans_eval .TransitionFormEntry = trans_entry End With
OPTIONS.VIEW(formula, status, notes, show_info, object_num, page_breaks, formulas, gridlines, color_num, headers, display_outline, zeros, hor_scroll, vert_scroll, sheet_tabs)	With Application .DisplayFormulaBar = formula .DisplayStatusBar = status .DisplayNoteIndicator = notes .DisplayInfoWindow = show_info End With ActiveWorkbook.DisplayDrawingObjects = object_num ActiveSheet.DisplayAutomaticPageBreaks = page_breaks With ActiveWindow .DisplayFormulas = formulas .DisplayGridlines = gridlines .GridlineColorIndex = color_num .DisplayHeadings = headers .DisplayOutline = display_outline .DisplayZeros = zeros .DisplayHorizontalScrollBar = hor_scroll .DisplayVerticalScrollBar = vert_scroll .DisplayWorkbookTabs = sheet_tabs End With
OUTLINE(auto_styles, row_dir, col_dir)	With ActiveSheet.Outline .AutomaticStyles = auto_styles .SummaryRow = row_dir .SummaryColumn = col_dir End With
Changes outline settings.

OUTLINE(, , , 1)	Selection.AutoOutline
Creates an outline with the current outline settings.

OUTLINE(, , , 2)	Selection.ApplyOutlineStyles
Applies outline styles to the outlined selection.

OVERLAY(type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle, series_num, auto)	With ActiveChart.ChartGroups(2) .Type = type_num .SubType = 100 .VaryByCategories = vary .Overlap = overlap% .HasDropLines = drop .HasHiLoLines = hilo .FirstSliceAngle = angle End With
This function is used only for backward compatability with Microsoft Excel version 2.2 or earlier. Some arguments don't apply to all chart types. The stack, overlap, cluster, series_num, and auto arguments have no direct equivalents in Microsoft Excel version 5.0 or later.

P

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)	With ActiveSheet.PageSetup .LeftHeader = head .CenterHeader = head .RightHeader = head . = foot .CenterFooter = foot .RightFooter = foot .LeftMargin = Application.InchesToPoints(left) .RightMargin = Application.InchesToPoints(right) .TopMargin = Application.InchesToPoints(top) .BottomMargin = Application.InchesToPoints(bot) .PrintHeadings = hdng .PrintGridlines = grid .CenterHorizontally = h_cntr .CenterVertically = v_cntr .Orientation = orient .PaperSize = paper_size If scale = True Then .Zoom = False .FitToPagesWide = 1 .FitToPagesTall = 1 ElseIf IsArray(scale) Then .Zoom = False If IsError(scale(1)) Then .FitToPagesWide = False Else .FitToPagesWide = scale(1) End If If IsError(scale(2)) Then .FitToPagesTall = False Else .FitToPagesWide = scale(2) End If Else .Zoom = scale End If .FirstPageNumber = pg_num .Order = pg_order .BlackAndWhite = bw_cells .PrintQuality = quality .HeaderMargin = _ Application.InchesToPoints(head_margin) .FooterMargin = _ Application.InchesToPoints(foot_margin) .PrintNotes = notes .Draft = draft End With
Controls page settings for worksheets and macro sheets. In Visual Basic, the head and foot arguments are split into separate left, center, and right format strings. Note also the translation required for the scale argument.

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)	With ActiveSheet.PageSetup .LeftHeader = head_margin .CenterHeader = head_margin .RightHeader = head_margin .LeftFooter = foot_margin .CenterFooter = foot_margin .RightFooter = foot_margin .LeftMargin = Application.InchesToPoints(left) .RightMargin = Application.InchesToPoints(right) .TopMargin = Application.InchesToPoints(top) .BottomMargin = Application.InchesToPoints(bot) .ChartSize = paper_size .CenterHorizontally = h_cntr .CenterVertically = v_cntr .Orientation = orient .PaperSize = paper_size .Zoom = scale .FirstPageNumber = pg_num .BlackAndWhite = bw_chart .PrintQuality = quality .HeaderMargin = _ Application.InchesToPoints(head_margin) .FooterMargin =  _ Application.InchesToPoints(foot_margin) .Draft = draft End With
Controls page settings for charts. In Visual Basic, the head and foot arguments are split into separate left, center, and right format strings.

PAGE.SETUP(head, foot, left, right, top, bot, orient, paper_size, scale, quality, head_margin, foot_margin, pg_num)	With ActiveSheet.PageSetup .LeftHeader = head .CenterHeader = head .RightHeader = head .LeftFooter = foot .CenterFooter = foot .RightFooter = foot .LeftMargin = Application.InchesToPoints(left) .RightMargin = Application.InchesToPoints(right) .TopMargin = Application.InchesToPoints(top) .BottomMargin = Application.InchesToPoints(bot) .Orientation = orient .PaperSize = paper_size .Zoom = scale .PrintQuality = quality .HeaderMargin = _ Application.InchesToPoints(head_margin) .FooterMargin =  _ Application.InchesToPoints(foot_margin) .FirstPageNumber = pg_num End With
Controls page settings for Visual Basic modules. In Visual Basic, the head and foot arguments are split into separate left, center, and right format strings.

PARSE(parse_text, destination_ref)	Selection.Parse parseLine := parse_text, _ destination := destination_ref
PASTE(to_reference)	ActiveSheet.Paste destination := to_reference
Pastes data onto a sheet or chart. If a chart is active, use the ActiveChart property instead of the ActiveSheet property, and omit the destination argument. Note that the Paste method is dependent on the current selection.

PASTE( )	Selection.Paste
Pastes an image onto the selected point or series in a picture chart.

PASTE( )	ActiveChart.Paste
Pastes an entire chart onto the active chart.

PASTE.LINK( )	ActiveSheet.Paste link := True
Establishes a link with the source of the data being pasted.

PASTE.PICTURE( )	ActiveSheet.Pictures.Paste
Pastes a picture of the data on the Clipboard. If the active sheet is a chart, use the ActiveChart property instead of the ActiveSheet property.

PASTE.PICTURE.LINK( )	ActiveSheet.Pictures.Paste link := True
Pastes a picture that's linked to the source of the data on the Clipboard. If the active sheet is a chart, use the ActiveChart property instead of the ActiveSheet property.

PASTE.SPECIAL(paste_num, operation_num, skip_blanks, transpose)	Selection.PasteSpecial paste := paste_num, _ operation := operation_num, skipBlanks := skip_blanks, _ transpose := transpose
Pastes worksheet or macro sheet range data.

PASTE.SPECIAL(rowcol, titles, categories, replace, series)	ActiveChart.SeriesCollection.Paste rowcol := rowcol, _ seriesLabels := titles, categoryLabels := categories, _ replace := replace, newSeries := series
Pastes data points or data series information onto a chart.

PASTE.SPECIAL(paste_num)	ActiveChart.Paste type := paste_num
Pastes chart information onto a chart.

PASTE.SPECIAL(format_text, pastelink_logical, display_icon_logical, icon_file, icon_number, icon_label)	ActiveSheet.PasteSpecial format := format_text, _ link := pastelink_logical, _ displayAsIcon := display_icon_logical, _ iconFileName := icon_file, iconIndex := icon_number, _ iconLabel := icon_label
Pastes data from another application.

PASTE.TOOL(bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).PasteFace
PATTERNS(apattern, afore, aback, TRUE)	With Selection.Interior If apattern = 0 Then .ColorIndex = xlNone Else .ColorIndex = aback .Pattern = apattern .PatternColorIndex = afore End If End With
Syntax 1: Sets pattern and color information for the selected range. Visual Basic has no direct equivalent if the newui argument is FALSE, which indicates Microsoft Excel version 4.0 compatibility mode.

PATTERNS(lauto, lstyle, lcolor, lwt, hwidth, hlength, htype)	With Selection.Border If lauto = 1 Then .LineStyle = xlAutomatic ElseIf lauto = 2 Then .LineStyle = xlNone Else .LineStyle = lstyle .ColorIndex = lcolor .Weight = lwt End If End With With Selection .ArrowHeadWidth = hwidth .ArrowHeadStyle = htype .ArrowHeadLength = hlength End With
Syntax 2: Sets color and line style information for lines and arrows on worksheets and charts.

PATTERNS(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, rounded, TRUE)	With Selection.Border If bauto = 1 Then .LineStyle = xlAutomatic ElseIf bauto = 2 Then .LineStyle = xlNone Else .LineStyle = bstyle .ColorIndex = bcolor .Weight = bwt End If End With Selection.Shadow = shadow With Selection.Interior If aauto = 1 Then .Pattern = xlAutomatic ElseIf aauto = 2 Then .Pattern = xlNone Else .ColorIndex = aback .Pattern = apattern .PatternColorIndex = afore End If End With Selection.RoundedCorners = rounded
Syntax 3: Sets pattern and border information for filled drawing objects on worksheets and charts. Visual Basic has no direct equivalent if the newui argument is FALSE, which indicates Microsoft Excel version 4.0 compatibility mode.

PATTERNS(bauto, bstyle, bcolor, bwt, shadow, aauto, apattern, afore, aback, invert, apply, TRUE)	With Selection.Border If bauto = 1 Then .LineStyle = xlAutomatic ElseIf bauto = 2 Then .LineStyle = xlNone Else .LineStyle = bstyle .ColorIndex = bcolor .Weight = bwt End If End With Selection.Shadow = shadow With Selection.Interior If aauto = 1 Then .Pattern = xlAutomatic ElseIf aauto = 2 Then .Pattern = xlNone Else .ColorIndex = aback .Pattern = apattern .PatternColorIndex = afore End If End With Selection.InvertIfNegative = invert
Syntax 4: Sets pattern and border information for chart bars, columns, areas, and text labels. Visual Basic has no direct equivalent if the newfill argument is FALSE, which indicates Microsoft Excel version 4.0 compatibility mode. The apply argument has no equivalent in Visual Basic.

PATTERNS(lauto, lstyle, lcolor, lwt, tmajor, tminor, tlabel)	With Selection.Border If bauto = 1 Then .LineStyle = xlAutomatic ElseIf bauto = 2 Then .LineStyle = xlNone Else .LineStyle = bstyle .ColorIndex = bcolor .Weight = bwt End If End With With Selection .MajorTickMark = tmajor .MinorTickMark = tminor .TickLabelPosition = tlabel End With
Syntax 5: Sets border and style information for chart axes.

PATTERNS(lauto, lstyle, lcolor, lwt, apply, smooth)	With Selection.Border If lauto = 1 Then .LineStyle = xlAutomatic ElseIf lauto = 2 Then .LineStyle = xlNone Else .LineStyle = lstyle .ColorIndex = lcolor .Weight = lwt End If End With Selection.Smooth = smooth
Syntax 6: Sets border information for chart lines other than chart data lines. The apply argument has no equivalent in Visual Basic.

PATTERNS(lauto, lstyle, lcolor, lwt, mauto, mstyle, mfore, mback, apply, smooth)	With Selection.Border If lauto = 1 Then .LineStyle = xlAutomatic ElseIf lauto = 2 Then .LineStyle = xlNone Else .LineStyle = lstyle .ColorIndex = lcolor .Weight = lwt End If End With With Selection If mauto = 1 Then .MarkerStyle = xlAutomatic ElseIf mauto = 2 Then .MarkerStyle = xlNone Else .MarkerStyle = mstyle .MarkerForegroundColorIndex = mfore .MarkerBackgroundColorIndex = mback End If .Smooth = smooth End With
Syntax 7: Sets border information for chart data lines. The apply argument has no equivalent in Visual Basic.

PATTERNS(type, picture_units, apply)	With Selection .PictureType = type .PictureUnit = picture_units End With
Syntax 8: Sets picture chart information for picture chart data markers. The apply argument has no equivalent in Visual Basic.

PAUSE(no_tool)
No direct equivalent. Use a breakpoint or the Stop statement to halt execution and show the Debug window. After you've halted the procedure, use the Immediate pane to examine and set variables.

PIVOT.ADD.DATA(name, pivot_field_name, new_name, position, function, calculation, base_field, base_item, format_text)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name) .Orientation = xlDataField .Name = new_name .Position = position .Function = function .Calculation = calculation .BaseField = base_field .BaseItem = base_item .NumberFormat = format_text End With
If the name argument is omitted, use ActiveCell.PivotTable instead of ActiveSheet.PivotTables(name). The same replacement can be used for all the following PivotTable functions that have a PivotTable name argument.

PIVOT.ADD.FIELDS(name, row_array, column_array, page_array, add_to_table)	ActiveSheet.PivotTables(name).AddFields _ rowFields := row_array, columnFields := column_array, _ pageFields := page_array, addToTable := add_to_table
PIVOT.FIELD(name, pivot_field_name, orientation, position)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name) .Orientation = orientation .Position = position End With
Pivots a specified field within a specified PivotTable.

PIVOT.FIELD(, , orientation, position)	With ActiveCell.PivotField .Orientation = orientation .Position = position End With
Pivots the field that contains the active cell.

PIVOT.FIELD.GROUP(start, end, by, periods)	Selection.Group start := start, end := end, by := by, _ periods := periods
Creates groups within a pivot field. In Visual Basic, the periods argument is an array of logical values specifying the date periods to group by. The Microsoft Excel 4.0 macro period argument must be converted from a summed number to an array of logical values.

PIVOT.FIELD.PROPERTIES(name, pivot_field_name, new_name, orientation, function, formats)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name) .Name = new_name .Orientation = orientation .Subtotals = function For x = 1 To UBound(formats, 1) .PivotItems(formats(x, 1)).Visible = formats(x, 2) Next End With
Changes the properties of a PivotTable header field. In Visual Basic, the Subtotals property is an array of logical values specifying the subtotals calculated for the field. The PIVOT.FIELD.PROPERTIES function argument must be converted from a summed number to an array of logical values. The formats argument is an array specifying the visibility of items in the field. Visual Basic requires that the properties of pivot items be set individually for each field. The example iterates over the array to set the Visible property according to the array contents.

PIVOT.FIELD.PROPERTIES(name, pivot_field_name, new_name, orientation, function, formats)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name) .Name = new_name .Orientation = orientation .Function = function .Calculation = formats(1) .BaseField = formats(2) .BaseItem = formats(3) .NumberFormat = formats(4) End With
Changes the properties of a PivotTable data field. In Visual Basic, the function argument is converted from an array to four distinct properties.

PIVOT.FIELD.UNGROUP( )	Selection.Ungroup
PIVOT.ITEM(name, pivot_field_name, pivot_item_name, position)	ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name). _ PivotItems(pivot_item_name).Position = position
Moves the specified item in a PivotTable.

PIVOT.ITEM(, , , position)	ActiveCell.PivotItem.Position = position
Moves the pivot item containing the active cell.

PIVOT.ITEM.PROPERTIES(name, pivot_field_name, pivot_item_name, new_name, position, show, TRUE)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name). _ PivotItems(pivot_item_name) .Name = new_name .Position = position .Visible = show End With ActiveSheet.PivotTables(name).PivotFields(pivot_field_name). _ CurrentPage = new_name
Changes the name and properties of a pivot item in a header field and makes the item the active item in the page field.

PIVOT.ITEM.PROPERTIES(name, pivot_field_name, pivot_item_name, , position, show, TRUE)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name). _ PivotItems(pivot_item_name) .Position = position .Visible = show End With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name).CurrentPage = _ pivot_item_name
Changes the properties of a pivot item in a header field and makes the item the active item in the page field.

PIVOT.ITEM.PROPERTIES(name, pivot_field_name, pivot_item_name, new_name, position, show, FALSE)	With ActiveSheet.PivotTables(name). _ PivotFields(pivot_field_name). _ PivotItems(pivot_item_name) .Name = new_name .Position = position .Visible = show End With
Changes the properties of a pivot item in a header field without changing the active item in the page field.

PIVOT.REFRESH(name)	ActiveSheet.PivotTables(name).RefreshTable
PIVOT.SHOW.PAGES(name, page_field)	ActiveSheet.PivotTables(name).ShowPages _ pageField := page_field
PIVOT.TABLE.WIZARD(type, source, destination, name, row_grand, col_grand, save_data, apply_auto_format, autopage)	ActiveSheet.PivotTableWizard sourceType := type, _ SourceData := source, tableDestination := destination, _ tableName := name, rowGrand := row_grand, _ columnGrand := col_grand, saveData := save_data, _ hasAutoFormat := apply_auto_format, _ autoPage := autopage
POKE(channel_num, item_text, data_ref)	Application.DDEPoke channel := channel_num, _ item := item_text, data_ref := data_ref
PRECISION(logical)	ActiveWorkbook.PrecisionAsDisplayed = logical
PREFERRED( )	ActiveChart.AutoFormat gallery := xlDefaultAutoFormat
PRESS.TOOL(bar_id, position, down)	Toolbars(bar_id).ToolbarButtons(position).Pushed = down
PRINT(1, , , copies, , preview, , , , , , 1)	Selection.PrintOut copies := copies, preview := preview
Prints all pages of the selection.

PRINT(2, from, to, copies, , preview, , , , , , 1)	Selection.PrintOut from := from, to := to, copies := copies, _ preview := preview
Prints the specified pages of the selection.

PRINT(1, , , copies, draft, preview, print_what, color, feed, quality, y_resolution, 1)	' Save the page setup variables to restore after override With ActiveSheet.PageSetup saveDraft = .Draft savePrintNotes = .PrintNotes ' Override the page setup settings .Draft = draft If print_what = 3 Then .PrintNotes = True Else .PrintNotes = False End If End With ' Print with overridden settings Selection.PrintOut copies := copies, preview := preview ' Restore page setup settings With ActiveSheet.PageSetup .Draft = saveDraft .PrintNotes = savePrintNotes End With
Prints all pages of the selection, temporarily overriding the draft quality and print notes settings selected during page setup. The color, feed, quality, and y_resolution arguments have no direct equivalents in Visual Basic. A print_what value of 2, which prints only notes, has no equivalent in Visual Basic.

PRINT(1, , , copies, draft, preview, , , , , , 2)	ActiveWindow.SelectedSheets.PrintOut copies := copies, _ preview := preview
Prints all pages of the selected sheets.

PRINT(1, , , copies, draft, preview, , , , , , 2)	Windows("Info").PrintOut copies := copies, preview := preview
Prints all pages of the Info window, if the Info window is the active window.

PRINT(1, , , copies, , preview, , , , , , 3)	ActiveWorkbook.PrintOut copies := copies, preview := preview
Prints all pages of the active workbook.

PRINT.PREVIEW( )	ActiveSheet.PrintPreview
Previews printing of the active sheet.

PRINT.PREVIEW( )	Windows("Info").PrintPreview
Previews printing of the Info window if it's the active window.

PRINTER.SETUP(printer_text)	Application.ActivePrinter = printer_text
PROMOTE(1)	Selection.Rows.Ungroup
Promotes, or ungroups, the rows in the selection. The parameter 1 is optional.

PROMOTE(2)	Selection.Columns.Ungroup
Promotes, or ungroups, the columns in the selection.

PROTECT.DOCUMENT(contents, windows, password, objects, scenarios)	ActiveSheet.Protect password := password, _ drawingObjects := objects, contents := contents, _ scenarios := scenarios
Protects the active sheet. The windows argument has no direct equivalent in Microsoft Excel version 5.0 or later.

PROTECT.DOCUMENT(FALSE, windows, password, FALSE, FALSE)	ActiveSheet.Unprotect password := password
Unprotects the active sheet. The windows argument has no direct equivalent in Microsoft Excel version 5.0 or later.

PUSHBUTTON.PROPERTIES( default_logical, cancel_logical, dismiss_logical, help_logical, accel_text, accel_text2)	With Selection .DefaultButton = default_logical .CancelButton = cancel_logical .DismissButton = dismiss_logical .HelpButton = help_logical .Accelerator = accel_text .PhoneticAccelerator = accel_text2 End With
Q

QUIT( )	Application.Quit


Visual Basic Equivalents R
Visual Basic Equivalents for Macro Functions and Commands

R

REFTEXT(reference, TRUE)	Range.Address referenceStyle := xlA1
No direct equivalent. In Visual Basic, the Range object is more flexible than the REFTEXT function and shouldn't require you to manipulate references as text. The example returns the range address as an absolute A1-style reference in text form (the REFTEXT function always preserves the absolute or relative nature of the original reference).

REFTEXT(reference, FALSE)	Range.Address referenceStyle := xlR1C1
No direct equivalent. The example returns the range address as an absolute R1C1-style reference in text form.

REGISTER("SAMPLE.DLL", "MyFunction", "AIC")	Declare Function MyFunction Lib "SAMPLE.DLL" _ (ByVal a As Integer, ByVal s As String) As Boolean
Registers a function in a DLL or code resource so that it can be called from the Microsoft Excel 4.0 macro language. In Visual Basic, the Declare statement registers DLL or code resource functions. The example shows registration of a single function in SAMPLE.DLL returning a Boolean value and taking an integer and a string parameter.

The remaining parameters of the REGISTER function have no direct equivalents in Visual Basic. These parameters control how the function appears in the Function Wizard and whether or not the function can be entered on a worksheet or macro sheet. You can make a DLL function available on a worksheet by using the ExecuteExcel4Macro method to run the REGISTER command.

REGISTER(module_text)	Application.RegisterXLL filename := module_text
Automatically registers all worksheet and Microsoft Excel 4.0 macro language functions within a DLL or code resource.

RELREF(reference, rel_to_ref)	Range(reference).Address rowAbsolute := False, _ columnAbsolute := False, referenceStyle := xlR1C1, _ relativeTo := Range(rel_to_ref)
REMOVE.LIST.ITEM(index_num, count_num)	Selection.RemoveItem index := index_num, count := count_num
REMOVE.PAGE.BREAK( )	ActiveCell.PageBreak = xlNone
Removes manual page breaks to the left of or above the active cell.

REMOVE.PAGE.BREAK( )	Cells.PageBreak = xlNone
Removes manual page breaks from the entire sheet if all cells are selected.

RENAME.COMMAND(bar_num, menu, command, name_text)	Menubars(bar_num).Menus(menu). _ MenuItems(command).Caption = name_text
Renames a command on a menu.

RENAME.COMMAND(bar_num, menu, command, name_text, position)	Menubars(bar_num).Menus(menu). _ MenuItems(command). _ MenuItems(position).Caption = name_text
Renames a command on a submenu.

RENAME.COMMAND(bar_num, menu, command, name_text)	ShortcutMenus(shortcut_menu). _ MenuItems(command).Caption = name_text
Renames a command on a shortcut menu. You access shortcut menus in Visual Basic by using the ShortcutMenus method with the appropriate constant.

RENAME.OBJECT(new_name)	Selection.Name = new_name
REPLACE.FONT(font_num, name_text, size_num, bold, italic, underline, strike, color, outline, shadow)
This function is provided only for macro compatability with previous versions of Microsoft Excel. It has no direct equivalent in Visual Basic. For information about changing fonts, see the FONT.PROPERTIES function.

REQUEST(channel_num, item_text)	Application.DDERequest channel := channel_num, _ item := item_text
RESET.TOOL(bar_id, position)	Toolbars(bar_id).ToolbarButtons(position).Reset
RESET.TOOLBAR(bar_id)	Toolbar(bar_id).Reset
RESTART(level_num)
No direct equivalent. In Visual Basic, you can use a GoTo statement to explicitly jump to a particular piece of code, but you cannot arbitrarily return from a called routine to a particular caller.

RESULT(type_num)	Function MyProcedure () As String
Specifies the return type of a function. In Visual Basic, the result of a function is declared as a part of the function header. The example shows a procedure returning a String value.

If the type_num parameter specifies more than one return type (for example, if you use the return type_num 5 to specify either a number (1) or a logical (4) return value), in Visual Basic you need to specify the return type as Variant.

RESUME(type_num)
No direct equivalent. You cannot pause Visual Basic macros. Instead, to assist in debugging a macro, Visual Basic provides the Debug window and breakpoints or watchpoints.

RETURN(value)	Function MyFunction () ' Often a function returns before reaching the normal ' end of the function, for example after an error occurs. If AnErrorOccurred Then MyFunction = value Exit Function End If ' No Exit Function is necessary at the end of the function ' because the End Function statement implies a return MyFunction = value End Function
Returns from a subroutine or function and specifies the return value. In Visual Basic, you specify the return value of a function by assigning the return value to the name of the function. A function yields its return value when the end of the function is reached at the End Function statement, or when an Exit Function statement is executed. The example shows assignment of the return value and illustrates the use of both forms of returning from a function.

ROUTE.DOCUMENT( )	ActiveWorkbook.Route
ROUTING.SLIP(recipients,subject, message, route_num, return_logical, status_logical)	ActiveWorkbook.HasRoutingSlip = True With ActiveWorkbook.RoutingSlip .Recipients = recipients .Subject = subject .Message = message .Delivery = route_num .ReturnWhenDone = return_logical .TrackStatus = status_logical End With
ROW.HEIGHT(, reference, , 1)	Rows(reference).Hidden = True
Hides rows. If you're hiding the selection, use Selection.EntireRow instead of the Rows method.

ROW.HEIGHT(, reference, , 2)	Rows(reference).Hidden = False
Unhides rows.

ROW.HEIGHT(, reference, , 3)	Rows(reference).AutoFit
Sizes the rows in reference to the height of the tallest item in each row.

ROW.HEIGHT(height_num, reference)	Rows(reference).RowHeight = height_num
Sets the row height to the specified value.

ROW.HEIGHT(, reference, TRUE)	Rows(reference).RowHeight = ActiveSheet.StandardHeight
Sets the row height to the standard row height value.

RUN(reference, step)	Application.Run macro := Range(reference)
Runs a particular macro. Visual Basic has no equivalent for the step parameter. Note that the Run method in Visual Basic can pass parameters and return values of the called macro. To run a Microsoft Excel 4.0 macro from Visual Basic, use the ExecuteExcel4Macro method of the Application object.

RUN(1)	ActiveWorkbook.RunAutoMacros which := xlAutoOpen
RUN(2)	ActiveWorkbook.RunAutoMacros which := xlAutoClose
RUN(3)	ActiveWorkbook.RunAutoMacros which := xlAutoActivate
RUN(4)	ActiveWorkbook.RunAutoMacros which := xlAutoDeactivate


Visual Basic Equivalents S
Visual Basic Equivalents for Macro Functions and Commands

S

SAVE( )	ActiveWorkbook.Save
SAVE.AS(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)	ActiveWorkbook.SaveAs filename := document_text, _ fileFormat := type_num, password := prot_pwd, _ writeResPassword := write_res_pwd, _ readOnlyRecommended := read_only_rec, _ createBackup := backup
SAVE.AS(, 0)	ActiveWorkbook.Saved = True
Changes the workbook so that Microsoft Excel will not prompt you to save it when you close it.

SAVE.COPY.AS(document_text)	ActiveWorkbook.SaveCopyAs filename := document_text
SAVE.DIALOG(init_filename, title, button_text, file_filter, filter_index)	Application.GetSaveAsFilename initialFilename := init_filename, fileFilter := file_filter, _ filterIndex := filter_index, title := title, _ buttonText := button_text
SAVE.TOOLBAR(bar_id, filename)	ExecuteExcel4Macro("SAVE.TOOLBAR(...)")
No direct equivalent.

SAVE.WORKBOOK(document_text, type_num, prot_pwd, backup, write_res_pwd, read_only_rec)	ActiveWorkbook.SaveAs filename := document_text, _ fileFormat := type_num, password := prot_pwd, _ writeResPassword := write_res_pwd, _ readOnlyRecommended := read_only_rec, _ createBackup := backup
SAVE.WORKSPACE(name_text)	Application.Save filename := name_text
SCALE(cross, cat_labels, cat_marks, between, max, reverse)	With ActiveChart.Axes(xlCategory, xlPrimary) If max = True Then .Crosses = xlMaximum Else .CrossesAt = cross End If .TickLabelSpacing = cat_labels .TickMarkSpacing = cat_marks .ReversePlotOrder = reverse .AxisBetweenCategories = between End With
Syntax 1: Controls settings for the category axes on a 2-D chart. If the secondary axis is selected, use xlSecondary instead of xlPrimary.

SCALE(min_num, max_num, major, minor, cross, logarithmic, reverse, max)	With ActiveChart.Axes(xlValue, xlPrimary) If min_num = True Then .MinimumScaleIsAuto = True Else .MinimumScale = min_num End If If max_num = True Then .MaximumScaleIsAuto = True Else .MaximumScale = max_num End If If major = True Then .MajorUnitIsAuto = True Else .MajorUnit = major End If If minor = True Then .MinorUnitIsAuto = True Else .MinorUnit = minor End If If max = True Then .Crosses = xlMaximum Else If cross = True Then .Crosses = xlAutomatic Else .Crosses = xlCustom .CrossesAt = cross End If End If .ScaleType = logarithmic .ReversePlotOrder = reverse End With
Syntax 2: Controls settings for the value axes on a 2-D chart. If the secondary axis is selected, use xlSecondary instead of xlPrimary.

SCALE(cat_labels, cat_marks, reverse, between)	With ActiveChart.Axes(xlCategory) .TickLabelSpacing = cat_labels .TickMarkSpacing = cat_marks .ReversePlotOrder = reverse .AxisBetweenCategories = between End With
Syntax 3: Controls settings for the category axis on a 3-D chart.

SCALE(series_labels, series_marks, reverse)	With ActiveChart.Axes(xlSeries) .TickLabelSpacing = series_labels .TickMarkSpacing = series_marks .ReversePlotOrder = reverse End With
Syntax 4: Controls settings for the series axis on a 3-D chart.

SCALE(min_num, max_num, major, minor, cross, logarithmic, reverse, min)	With ActiveChart.Axes(xlValue) If min_num = True Then .MinimumScaleIsAuto = True Else .MinimumScale = min_num End If If max_num = True Then .MaximumScaleIsAuto = True Else .MaximumScale = max_num End If If major = True Then .MajorUnitIsAuto = True Else .MajorUnit = major End If If minor = True Then .MinorUnitIsAuto = True Else .MinorUnit = minor End If If min = True Then .Crosses = xlMinimum Else If cross = True Then .Crosses = xlAutomatic Else .Crosses = xlCustom .CrossesAt = cross End If End If .ScaleType = logarithmic .ReversePlotOrder = reverse End With
Syntax 5: Controls settings for the value axis on a 3-D chart.

SCENARIO.ADD(scen_name, value_array, changing_ref, scen_comment, locked, hidden)	ActiveSheet.Scenarios.Add name := scen_name, _ changingCells := changing_ref, values := value_array, _ comment := scen_comment, locked := locked, _ hidden := hidden
SCENARIO.CELLS(changing_ref)	For Each scen In ActiveSheet.Scenarios scen.ChangeScenario changingCells := changing_ref Next
No direct equivalent. Scenarios in Microsoft Excel version 5.0 or later can have different sets of changing cells; however, the SCENARIO.CELLS command assumes that there is only one set of changing cells. To simulate having only a single set of changing cells, the example sets the changing cells of all scenarios by using a loop.

SCENARIO.DELETE(scen_name)	ActiveSheet.Scenarios(scen_name).Delete
SCENARIO.EDIT(scen_name, new_scenname, value_array, changing_ref, scen_comment, locked, hidden)	ActiveSheet.Scenarios.ChangeScenario _ changingCells := changing_ref, values := value_array With ActiveSheet.Scenarios(scen_name) .Name = new_scenname .Comment = scen_comment .Locked = locked .Hidden = hidden End With
SCENARIO.GET(1)	Dim result() As String count = 0 For Each scen In ActiveSheet.Scenarios count = count + 1 ReDim Preserve result(1 To count) result(count) = scen.Name Next
Returns an array of the scenario names defined on the current sheet. Visual Basic uses the Scenarios collection for accessing scenarios, allowing direct iteration. The example builds an array of the scenario names by using the Scenarios collection.

SCENARIO.GET(2, scen_name)	ActiveSheet.Scenarios(scen_name).ChangingCells
SCENARIO.GET(3)	ExecuteExcel4Macro("SCENARIO.GET(3)")
No direct equivalent.

SCENARIO.GET(4, scen_name)	ActiveSheet.Scenarios(scen_name).Values
SCENARIO.GET(5, scen_name)	ActiveSheet.Scenarios(scen_name).Comment
SCENARIO.GET(6, scen_name)	ActiveSheet.Scenarios(scen_name).Locked
SCENARIO.GET(7, scen_name)	ActiveSheet.Scenarios(scen_name).Hidden
SCENARIO.GET(8, scen_name)	ExecuteExcel4Macro("SCENARIO.GET(8, scen_name)")
No direct equivalent

SCENARIO.MERGE(source_file)	ActiveSheet.Scenarios.Merge source := source_file
SCENARIO.SHOW(scen_name)	ActiveSheet.Scenarios(scen_name).Show
SCENARIO.SHOW.NEXT( )	ExecuteExcel4Macro("SCENARIO.SHOW.NEXT()")
No direct equivalent. Microsoft Excel version 5.0 or later doesn't have a next scenario button in the Scenarios dialog box, so Visual Basic doesn'y have a Next property. You can re-create the functionality of SCENARIO.SHOW.NEXT in Visual Basic by showing a specific scenario and maintaining a counter to remember which scenario is currently visible. Show the next scenario by incrementing the counter.

SCENARIO.SUMMARY(result_ref, report_type)	ActiveSheet.Scenarios.CreateSummary _ reportType := report_type, resultCells := result_ref
SCROLLBAR.PROPERTIES(value, min, max, inc, page, link, 3d_shading)	With Selection .Value = value .Min = min .Max = max .SmallChange = inc .LargeChange = page .LinkedCell = link .Display3DShading = 3d_shading End With
SELECT(selection, active_cell)	Range(selection).Select Range(active_cell).Activate
Selects cell ranges or changes the active cell.

SELECT("Oval 1", replace)	ActiveSheet.DrawingObjects("Oval 1").Select replace := replace
Selects a single drawing object on a sheet or chart. Use the ActiveChart property instead of the ActiveSheet property if the object is on a chart.

SELECT("Oval 1, Rectangle 2", replace)	ActiveSheet.DrawingObjects( _ Array("Oval 1", "Rectangle 2")).Select replace := replace
Selects multiple drawing objects on a sheet or chart. Use the ActiveChart property instead of the ActiveSheet property if the object is on a chart.

SELECT(item_text, single_point)
Selects items in a chart. The syntax of selecting items in charts varies widely. To see the Visual Basic equivalent of selecting a particular item in a chart, use the Record Macro command on the Tools menu.

SELECT.ALL( )	Set curSheet = ActiveSheet ActiveWorkbook.Sheets.Select curSheet.Activate
SELECT.CHART( )	ActiveChart.ChartArea.Select
SELECT.END(direction_num)	Selection.End(direction_num).Select
SELECT.LAST.CELL( )	ActiveCell.SpecialCells(xlLastCell).Select
SELECT.LIST.ITEM(index_num)	Selection.Value = index_num
Selects an item in a single-selection list box.

SELECT.LIST.ITEM(index_num, selected_logical)	Selection.Selected(index_num) = selected_logical
Selects or cancels the selection of an item in a multiple-selection list box.

SELECT.PLOT.AREA( )	ActiveChart.PlotArea.Select
SELECT.SPECIAL(1)	Selection.SpecialCells(xlNotes).Select
SELECT.SPECIAL(2, value_type)	Selection.SpecialCells(xlFormulas, value_type).Select
SELECT.SPECIAL(3, value_type)	Selection.SpecialCells(xlFormulas, value_type).Select
SELECT.SPECIAL(4)	Selection.SpecialCells(xlBlanks).Select
SELECT.SPECIAL(5)	Selection.CurrentRegion.Select
SELECT.SPECIAL(6)	Selection.CurrentArray.Select
SELECT.SPECIAL(7)	Selection.RowDifferences(ActiveCell).Select
SELECT.SPECIAL(8)	Selection.ColumnDifferences(ActiveCell).Select
SELECT.SPECIAL(9, , 1)	Selection.DirectPrecedents.Select
SELECT.SPECIAL(9, , 2)	Selection.Precedents.Select
SELECT.SPECIAL(10, , 1)	Selection.DirectDependents.Select
SELECT.SPECIAL(10, , 2)	Selection.Dependents.Select
SELECT.SPECIAL(11)	Selection.SpecialCells(xlLastCell).Select
SELECT.SPECIAL(12)	Selection.SpecialCells(xlVisible).Select
SELECT.SPECIAL(13)	ActiveSheet.DrawingObjects.Select
SELECTION( )	Selection
SEND.KEYS(key_text, wait_logical)	SendKeys key_text, wait_logical
SEND.MAIL(recipients, subject, return_receipt)	ActiveWorkbook.SendMail recipients := recipients, _ subject := subject, returnReceipt := return_receipt
SEND.TO.BACK( )	Selection.SendToBack
SERIES(name_ref, categories, values, plot_order)
No direct equivalent. The SERIES function represents the formula of a chart series and cannot be entered in a macro sheet cell. In Visual Basic, use the Name, Values, XValues, and PlotOrder properties of the Series object, and use the CategoryNames property of the Axis object.

SERIES.AXES(axis)	Selection.AxisGroup = axis
SERIES.ORDER(chart_num, old_series_num, new_series_num)	ActiveChart.ChartGroups(chart_num). _ SeriesCollection(old_series_num).PlotOrder = _ new_series_num
SERIES.X(x_ref)	Selection.XValues = x_ref
SERIES.Y(name_ref, y_ref)	With Selection .Name = name_ref .Values = y_ref End With
SET.CONTROL.VALUE(value)	Selection.Value = value
SET.CRITERIA( )	ExecuteExcel4Macro("SET.CRITERIA()")
No direct equivalent. The AdvancedFilter method in Visual Basic allows the criteria to be contained in any arbitrary range. Explicitly setting the criteria range isn't required.

SET.DATABASE( )	ExecuteExcel4Macro("SET.DATABASE()")
No direct equivalent. In Microsoft Excel version 5.0 or later, the database commands automatically detect and select database lists.

SET.DIALOG.DEFAULT(object_id_text)	ActiveDialog.DefaultButton = object_id_text
SET.DIALOG.FOCUS(object_id_text)	ActiveDialog.Focus = object_id_text
SET.EXTRACT( )	ExecuteExcel4Macro("SET.EXTRACT()")
No direct equivalent. The AdvancedFilter method in Visual Basic allows the extract to be contained in any arbitrary range. Explicitly setting the extract range isn't required.

SET.LIST.ITEM(text, index_num)	Selection.List(index_num) = text
SET.NAME(name_text, value)	Dim name_text name_text = value
Defines a temporary name while a macro is executing. In Visual Basic, use a variable instead of a name to hold a value. The example illustrates declaring a variable and assigning a value to it. Declaration of variables isn't necessary unless Option Explicit is used for the Visual Basic module.

SET.PAGE.BREAK( )	ActiveCell.PageBreak = xlManual
SET.PREFERRED(format)	Application.SetDefaultChart formatName := format
Sets the default chart format to the name of a custom autoformat.

SET.PREFERRED("Built-in")	Application.SetDefaultChart formatName := xlBuiltIn
Sets the default chart format to the standard built-in format.

SET.PRINT.AREA( )	ActiveSheet.PageSetup.PrintArea = Selection.Address
Sets the print area to match the current selection.

SET.PRINT.AREA(range)	ActiveSheet.PageSetup.PrintArea = range
Sets the print area to the specified range.

SET.PRINT.TITLES(titles_for_columns_ref, titles_for_rows_ref)	With ActiveSheet.PageSetup .PrintTitleColumns = titles_for_columns_ref .PrintTitleRows = titles_for_rows_ref End With
SET.UPDATE.STATUS(link_text, status, type_of_link)	ExecuteExcel4Macro("SET.UPDATE.STATUS(...)")
No direct equivalent.

SET.VALUE(reference, values)	myVariable = values
Changes the value of a name defined for the macro. In Visual Basic, use a variable instead of a name to hold a value while a macro is running. The example illustrates assigning a value to a variable.

SHORT.MENUS(TRUE)	MenuBars(xlWorksheetShort).Activate
Displays short menus. Visual Basic doesn't have a direct equivalent. This command is used for compatibility with Microsoft Excel version 3.0. The example displays the short worksheet menu bar.

SHOW.ACTIVE.CELL( )	ActiveCell.Activate
SHOW.BAR(bar_num)	MenuBars(bar_num).Activate
SHOW.CLIPBOARD( )	Application.DisplayClipboardWindow = True
SHOW.DETAIL(1, rowcol_num, expand)	Rows(rowcol_num).ShowDetail = expand
Shows or hides detail for an outline row.

SHOW.DETAIL(2, rowcol_num, expand)	Columns(rowcol_num).ShowDetail = expand
Shows or hides detail for an outline column.

SHOW.DETAIL(3, , expand, show_field)	ActiveCell.PivotTable.InnerDetail = show_field Selection.ShowDetail = expand
Shows or hides detail for a range in a PivotTable.

SHOW.DIALOG(dialog_sheet)	DialogSheets(dialog_sheet).Show
SHOW.INFO(logical)	Application.DisplayInfoWindow = logical
SHOW.LEVELS(row_level, col_level)	ActiveSheet.Outline.ShowLevels rowLevels := row_level, _ columnLevels = col_level
SHOW.TOOLBAR(bar_id, visible, dock, x_pos, y_pos, width, protect)	With Toolbars(bar_id) .Visible = visible .Position = dock .Left = x_pos .Top = y_pos .Width = width End With
Sets attributes for a toolbar. The protect argument has no equivalent in Visual Basic.

SHOW.TOOLBAR(0, , , , , , , tool_tips, large_buttons, color_buttons)	With Application .ShowToolTips = tool_tips .LargeButtons = large_buttons .ColorButtons = color_buttons End With
Sets toolbar workspace properties.

SORT(orientation, key1, order1, key2, order2, key3, order3, header, custom, case)	Selection.Sort key1 := key1, order1 := order1, _ key2 := key2, order2 := order2, _ key3 := key3, order3 := order3, _ header := header, orderCustom := custom, _ matchCase := case, orientation := orientation
Syntax 1: Sorts a range of cells.

SORT(orientation, key1, order1, type, custom)	Selection.Sort key1 := key1, order1 := order1, type := type _ orderCustom := custom, orientation := orientation
Syntax 2: Sorts a PivotTable.

SOUND.NOTE(cell_ref, FALSE)	Range(cell_ref).SoundNote.Record
Records a sound by displaying the sound recording dialog box.

SOUND.NOTE(cell_ref, TRUE)	Range(cell_ref).SoundNote.Delete
Deletes a sound note.

SOUND.NOTE(cell_ref, file_text, resource)	Range(cell_ref).SoundNote.Import filename := file_text _ resource := resource
Imports a sound note from a file. The resource argument is used Microsoft Excel for the Macintosh only.

SOUND.PLAY(cell_ref)	Range(cell_ref).SoundNote.Play
Plays a sound note contained in a cell. If cell_ref is omitted, use the ActiveCell property instead of Range(cell_ref).

SOUND.PLAY(, file_text, resource)	ExecuteExcel4Macro("SOUND.PLAY(, file_text, resource)")
Plays a sound contained in a file. Visual Basic has no direct equivalent.

SPELLING(custom_dic, ignore_uppercase, always_suggest)	Selection.CheckSpelling customDictionary := custom_dic, _ ignoreUppercase := ignore_uppercase, _ alwaysSuggest := always_suggest
SPELLING.CHECK(word_text, custom_dic, ignore_uppercase)	Application.CheckSpelling word := word_text, _ customDictionary := custom_dic, _ ignoreUppercase := ignore_uppercase
SPLIT(col_split, row_split)	With ActiveWindow .SplitColumn = col_split .SplitRow = row_split End With
STANDARD.FONT(name_text, size_num, bold, italic, underline, strike, color, outline, shadow)
This function is used for macro compatability with previous versions of Microsoft Excel. See the DEFINE.STYLE and APPLY.STYLE functions.

STANDARD.WIDTH(standard_num)	ActiveSheet.StandardWidth = standard_num
STEP( )	Stop
STYLE(bold, italic)
This function is used for macro compatability with previous versions of Microsoft Excel. See the FONT.PROPERTIES function.

SUBSCRIBE.TO(file_text, format_num)	Selection.SubscribeTo edition := file_text, format := format_num
SUBTOTAL.CREATE(at_change_in, function_num, total, replace, pagebreaks, summary_below)	Selection.Subtotal groupBy := at_change_in, _ function := function_num, totalList := total, _ replace := replace, pageBreaks := pagebreaks, _ summaryBelowData := summary_below
SUBTOTAL.REMOVE()	Selection.RemoveSubtotal
SUMMARY.INFO(title, subject, author, keywords, comments)	With ActiveWorkbook .Title = title .Subject = subject .Author = author .Keywords = keywords .Comments = comments End With


Visual Basic Equivalents T through Z
Visual Basic Equivalents for Macro Functions and Commands

T

TAB.ORDER()	Application.Dialogs(xlDialogTabOrder).Show
No direct equivalent. Use the Show method of the Dialogs collection to bring up the Tab Order dialog box, or use the BringToFront and SendToBack methods to control the tab order of controls on dialog sheets.

TABLE(row_ref, column_ref)	Selection.Table rowInput := row_ref, columnInput := column_ref
TERMINATE(channel_num)	DDETerminate channel := channel_num
TEXT.BOX(add_text, , start_num, num_chars)	Selection.Characters(start_num, num_chars).Text = add_text
Replaces text in the selected text box with add_text.

TEXT.BOX(add_text, object_id_text, start_num, num_chars)	ActiveSheet.DrawingObjects(object_id_text). _ Characters(start_num, num_chars).Text = add_text
Replaces text in a named text box or button with add_text.

TEXT.TO.COLUMNS(destination_ref, data_type, text_delim, consecutive_delim, tab, semicolon, comma, space, other, other_char, field_info)	Selection.TextToColumns destination := destination_ref, _ dataType := data_type, textQualifier := text_delim, _ consecutiveDelimiter := consecutive_delim, _ tab := tab, semicolon := semicolon, comma := comma, _ space := space, other := other_char, _ otherChar := other_char, fieldInfo := field_info
TEXTREF(text, TRUE)	Range(text)
Converts A1-style text to a reference. In Visual Basic, the Range method always takes A1-style text and returns a Range object.

TEXTREF(text, FALSE)	a1Text = Application.ConvertFormula(formula := "=" & text, _ fromReferenceStyle := xlR1C1, _ toReferenceStyle := xlA1, toAbsolute := xlAbsolute) Set result = Range(Right(a1Text, Len(a1Text) - 1))
No direct equivalent. Converts R1C1-style text to a reference. In Visual Basic, the Range method takes A1-style text only. The example translates R1C1-style text to A1-style text by treating the text as a formula.

R1C1-style text is often used in Microsoft Excel 4.0 macros to construct references from row and column indexes. In Visual Basic, use the Cells method, which constructs a Range object directly from numeric row and column index parameters.

TRACER.CLEAR( )	ActiveSheet.ClearArrows
TRACER.DISPLAY(FALSE, FALSE)	Selection.ShowDependents remove := True
Removes one level of dependent tracer arrows.

TRACER.DISPLAY(FALSE, TRUE)	Selection.ShowDependents remove := False
Adds one level of dependent tracer arrows.

TRACER.DISPLAY(TRUE, FALSE)	Selection.ShowPrecedents remove := True
Removes one level of precedent tracer arrows.

TRACER.DISPLAY(TRUE, TRUE)	Selection.ShowPrecedents remove := False
Adds one level of precedent tracer arrows.

TRACER.ERROR()	Selection.ShowErrors.Select
TRACER.NAVIGATE(direction, arrow_num, ref_num)	ActiveCell.NavigateArrow towardPrecedent := direction, _ arrowNumber := arrow_num, linkNumber := ref_num
U

UNDO( )	Application.Undo
UNGROUP( )	Selection.Ungroup
UNHIDE(window_text)	Windows(window_text).Visible = False
Unhides a normal workbook window.

UNHIDE("[Book1]Sheet1 Chart1")	ActiveSheet.ChartObjects("Chart 1").Activate
Activates an embedded chart for editing.

UNLOCKED.NEXT( )	ActiveCell.Next.Activate
UNLOCKED.PREV( )	ActiveCell.Previous.Activate
UNREGISTER(register_id)	ExecuteExcel4Macro("UNREGISTER(register_id)")
No direct equivalent. In Visual Basic, functions in DLLs and code resources are explicitly declared before use. At run time, Visual Basic loads, registers, and unregisters the functions automatically.

UPDATE.LINK(link_text, type_of_link)	ActiveWorkbook.UpdateLink name := link_text, _ type := type_of_link
V

VBA.MAKE.ADDIN( )	ExecuteExcel4Macro("VBA.MAKE.ADDIN")
No direct equivalent.

VBA.INSERT.FILE(filename_text)	ActiveSheet.InsertFile filename := filename_text
VIEW.3D(elevation, perspective, rotation, axes, height%, autoscale)	With ActiveChart .Elevation = elevation .Perspective = perspective .Rotation = rotation .RightAngleAxes = axes .HeightPercent = height% .AutoScaling = autoscale End With
VLINE(num_rows)	ActiveWindow.SmallScroll down := num_rows
VOLATILE(logical)	Application.Volatile volatile := logical
VPAGE(num_windows)	ActiveWindow.LargeScroll down := num_windows
VSCROLL(position, TRUE)	ActiveWindow.ScrollRow = position
Scrolls vertically to a specific row number.

VSCROLL(position, FALSE)	ActiveWindow.ScrollRow = position * 16384
Scrolls vertically to a fractional position. In Visual Basic, you can scroll to specific rows only. The example converts a fraction to an absolute row number.

W

WAIT(serial_number)	Application.Wait time := serial_number
WHILE(logical_test)	Do While logical_test ' statements within loop Loop
In Visual Basic, use a Do...Loop statement to build a loop. The Do...Loop statement offers more flexibility than the WHILE command.

WINDOW.MAXIMIZE( )	ActiveWindow.WindowState = xlMaximized
Maximizes the active document window.

WINDOW.MAXIMIZE(window_text)	Windows(window_text).WindowState = xlMaximized
Maximizes the specified window. For all the following WINDOW functions that have a window_text argument, use Windows(window_text) instead of the ActiveWindow property to manipulate a particular window.

WINDOW.MINIMIZE( )	ActiveWindow.WindowState = xlMinimized
WINDOW.MOVE(x_pos, y_pos)	With ActiveWindow .Left = x_pos .Top = y_pos End With
WINDOW.RESTORE( )	ActiveWindow.WindowState = xlNormal
WINDOW.SIZE(width, height)	With ActiveWindow .Width = width .Height = height End With
WINDOW.TITLE(text)	ActiveWindow.Caption = text
Changes the title text of a window.

WINDOW.TITLE( )	ExecuteExcel4Macro "WINDOW.TITLE()"
Restores the title text of a window to the default title. No direct equivalent.

WINDOWS( )	For Each w In Windows MsgBox w.Caption Next
Returns an array of window names. In Visual Basic, the Windows collection provides direct access to Window objects and doesn't require you to use text names. The example displays the name of each window in a message box.

WINDOWS(, match_text)	Dim result() As String numWindows = 0 For Each w In Windows If w.Caption Like match_text Then numWindows = numWindows + 1 ReDim Preserve result(1 To numWindows) result(numWindows) = w.Caption End If Next
Returns an array of window names with titles that match a given pattern. The example constructs an array of window names that match the pattern. Note the use of the Windows collection in a For Each...Next statement.

WINDOWS(2, match_text)
No equivalent. In Visual Basic, you cannot access the windows of loaded add-in workbooks.

WINDOWS(3, match_text)
No exact equivalent. In Visual Basic, you cannot access the windows of loaded add-in workbooks. You can access the windows of other workbooks by using the Windows collection.

WORKBOOK.ACTIVATE(sheet_name)	ActiveWorkbook.Sheets(sheet_name).Activate
WORKBOOK.ADD(name_array, dest_book, position_num)
Equivalent to WORKBOOK.MOVE in Microsoft Excel version 5.0 or later. See WORKBOOK.MOVE for Visual Basic equivalents.

WORKBOOK.COPY(name_array)	Sheets(name_array).Copy
Copies the specified sheets into a new workbook.

WORKBOOK.COPY(name_array, dest_book, position_num)	Sheets(name_array).Copy before := Sheets(position_num)
Copies the specified sheets and inserts the copies in the current workbook, assuming that dest_book is the name of the current workbook.

WORKBOOK.COPY(name_array, dest_book)	Sheets(name_array).Copy after := Sheets(Sheets.Count)
Copies the specified sheets and inserts the copies at the end of the current workbook, assuming that dest_book is the name of the current workbook.

WORKBOOK.COPY(name_array, dest_book, position_num)	Sheets(name_array).Copy before := _ Workbooks(dest_book).Sheets(position_num)
Copies the specified sheets and inserts the copies in a different workbook, assuming that dest_book isn't the name of the current workbook.

WORKBOOK.COPY(name_array, dest_book)	numSheets = Workbooks(dest_book).Sheets.Count Set LastInBook = Workbooks(dest_book).Sheets(numSheets) Sheets(name_array).Copy after := LastInBook
Copies the specified sheets and inserts the copies at the end of a different workbook, assuming that dest_book isn't the name of the current workbook.

WORKBOOK.DELETE( )	ActiveWindow.SelectedSheets.Delete
Deletes the selected sheets.

WORKBOOK.DELETE(sheet_text)	Sheets(sheet_text).Delete
Deletes the specified sheet.

WORKBOOK.DELETE({"Sheet1", "Sheet2"})	Sheets(Array("Sheet1", "Sheet2")).Delete
Deletes a set of sheets.

WORKBOOK.HIDE( )	ActiveWindow.SelectedSheets.Visible = False
Hides the selected sheets in the current workbook window.

WORKBOOK.HIDE(sheet_text)	Sheets(sheet_text).Visible = False
Hides the specified sheet.

WORKBOOK.HIDE({"Sheet1","Sheet2"})	Sheets(Array("Sheet1", "Sheet2")).Visible = False
Hides the set of sheets specified as an array.

WORKBOOK.HIDE(sheet_text, TRUE)	Sheets(sheet_text).Visible = xlVeryHidden
Hides the specified sheet so that it's not displayed in the unhide list.

WORKBOOK.INSERT(1)	Worksheets.Add
WORKBOOK.INSERT(2)	Charts.Add
WORKBOOK.INSERT(3)	Worksheets.Add type := xlExcel4MacroSheet
WORKBOOK.INSERT(4)	Worksheets.Add type := xlExcel4IntlMacroSheet
WORKBOOK.INSERT(6)	Modules.Add
WORKBOOK.INSERT(7)	DialogSheets.Add
WORKBOOK.MOVE(name_array)	Sheets(name_array).Move
Moves the specified sheets into a new workbook.

WORKBOOK.MOVE(name_array, dest_book, position_num)	Sheets(name_array).Move before := Sheets(position_num)
Moves the specified sheets within the current workbook, assuming that dest_book is the name of the current workbook.

WORKBOOK.MOVE(name_array, dest_book)	Sheets(name_array).Move after := Sheets(Sheets.Count)
Moves the specified sheets to the end of the current workbook, assuming that dest_book is the name of the current workbook.

WORKBOOK.MOVE(name_array, dest_book, position_num)	Sheets(name_array).Move before := _ Workbooks(dest_book).Sheets(position_num)
Moves the specified sheets to a different workbook, assuming that dest_book isn't the name of the current workbook.

WORKBOOK.MOVE(name_array, dest_book)	numSheets = Workbooks(dest_book).Sheets.Count Set LastInBook = Workbooks(dest_book).Sheets(numSheets) Sheets(name_array).Move after := LastInBook
Moves the specified sheets to the end of a different workbook, assuming that dest_book isn't the name of the current workbook.

WORKBOOK.NAME(oldname_text, newname_text)	Sheets(oldname_text).Name =  newname_text
WORKBOOK.NEW( )
No direct equivalent. This function adds a new sheet to a workbook after prompting the user for the sheet type. To add a particular type of sheet, use the Add method of the Sheets object.

WORKBOOK.NEXT( )	ActiveSheet.Next.Select
WORKBOOK.OPTIONS(sheet_name, , new_name)	Sheets(sheet_name).Name = new_name
The second argument of WORKBOOK.OPTIONS has no equivalent in Microsoft Excel version 5.0 or later.

WORKBOOK.PREV( )	ActiveSheet.Previous.Select
WORKBOOK.PROTECT(structure, windows, password)	ActiveWorkbook.Protect password := password, _ structure := structure, windows := windows
Protects a workbook if either structure or windows are TRUE.

WORKBOOK.PROTECT(FALSE, FALSE, password)	ActiveWorkbook.Unprotect password := password
Unprotects a workbook.

WORKBOOK.SCROLL(num_sheets)	ActiveWindow.ScrollWorkbookTabs sheets := num_sheets
Scrolls through the workbook tabs.

WORKBOOK.SCROLL(, TRUE)	ActiveWindow.ScrollWorkbookTabs position := xlLast
Scrolls through the workbook tabs to the last tab in the workbook.

WORKBOOK.SCROLL(, FALSE)	ActiveWindow.ScrollWorkbookTabs position := xlFirst
Scrolls through the workbook tabs to the first tab in the workbook.

WORKBOOK.SELECT("Sheet1", "Sheet1")	Sheets("Sheet1").Select
Selects a single sheet in the active workbook. This is the most common use of WORKBOOK.SELECT.

WORKBOOK.SELECT({"Sheet1", "Sheet2"}, "Sheet2")	Sheets(Array("Sheet1", "Sheet2")).Select Sheets("Sheet2").Activate
Selects a set of sheets in the active workbook and makes Sheet2 the active sheet in the group selection. In Visual Basic, this action requires you to first select the sheets and then specify which sheet should be active.

WORKBOOK.SELECT("Sheet1", "Sheet1", FALSE)	Sheets("Sheet1").Select replace := False
Adds a single sheet to the sheet selection in a workbook. With the Select method of the Sheet object, the replace argument works exactly the way it does for the WORKBOOK.SELECT function.

WORKBOOK.TAB.SPLIT(ratio_num)	ActiveWindow.TabRatio = (ratio_num)
WORKBOOK.UNHIDE(sheet_text)	Sheets(sheet_text).Visible = True
WORKGROUP({"Sheet1", "Sheet2"})	Sheets(Array("Sheet1", "Sheet2")).Select
Selects the specified sheets as part of a group edit. Visual Basic has no direct equivalent for this command when the sheet array is omitted.

WORKSPACE(fixed, decimals, r1c1, scroll, status, formula, menu_key, remote, entermove, underlines, tools, notes, nav_keys, menu_key_action, drag_drop, show_info, incell_edit)	With Application .FixedDecimal = fixed .FixedDecimalPlaces = decimals .ReferenceStyle = r1c1 .DisplayStatusBar = status .DisplayFormulaBar = formula .TransitionMenuKey = menu_key_action .IgnoreRemoteRequests = remote .MoveAfterReturn = entermove .CommandUnderlines = underlines .DisplayNoteIndicator = notes .TransitionNavigKeys = nav_keys .TransitionMenuKeyAction = menu_key_action .CellDragAndDrop = drag_drop .DisplayInfoWindow = show_info .EditDirectlyInCell = incell_edit End With With ActiveWindow .DisplayHorizontalScrollBar = scroll .DisplayVerticalScrollBar = scroll End With
The tools argument has no direct equivalent in Microsoft Excel version 5.0 or later.

X

Y

Z

ZOOM(TRUE)	ActiveWindow.Zoom = TRUE
ZOOM(FALSE)	ActiveWindow.Zoom = 100
ZOOM(magnification)	ActiveWindow.Zoom = magnification


More about converting Microsoft Excel version 4.0 macros to Visual Basic procedures

Tip	You can record macros in both Visual Basic and the Microsoft Excel 4.0 macro language. Comparing the same actions recorded in both languages can be very instructive in learning Visual Basic.

In many cases, some translation must occur between arguments to Microsoft Excel 4.0 macro language functions and Visual Basic properties or methods. Common scenarios where translation must occur include the following:

References    The Microsoft Excel 4.0 macro language reference data type is a direct representation of a cell address or range of cells on a worksheet or macro sheet, such as $C$10. You can enter a reference directly in a Microsoft Excel 4.0 macro language expression, because the macro sheet supports references. Visual Basic has an eqivalent data type, the Range object; however, the means of creating and manipulating ranges differ from those for references. You cannot enter Visual Basic ranges directly; you must create them by using a set of numeric row and column cell indexes, or by expressing the range address as A1-style text. For example, either Application.Range(Cells(1, 1), Cells(10, 10)) or Application.Range("A1:J10") returns the range A1 through J10.

Constants as arguments    Many macro functions take numbers as arguments. For example, INSERT(2) means shift cells down when inserting new cells. In Visual Basic, methods and properties use text constants instead of numbers for arguments. For example, in the Visual Basic statement Range("A1:C5").Insert(xlDown), xlDown means shift cells down when inserting new cells.

Making selections in macros    Most Microsoft Excel version 4.0-style macros implicitly operate on the selection or the active sheet. Visual Basic methods and properties, on the other hand, rarely operate on the selection. Instead, you must explicitly specify the object you want to work on. This gives you the flexibility of using objects that aren't active or selected. In some cases, Visual Basic treats objects in a fundamentally different manner than does the Microsoft Excel 4.0 macro language. In these cases, there may be no direct translation of a Microsoft Excel 4.0 macro language expression.

Functions in Add-ins    Microsoft Excel version 4.0 macro functions contained in add-ins remain the same in Visual Basic. You access these functions by making a reference to the add-in, using the References command (Tools menu) when a Visual Basic module is active. After you've done this, you can include the Microsoft Excel version 4.0 macro functions in your procedure. For example, you can write the following code to use the ANOVA macro function after you've used the References command.

Sub Analyze_Data

Anova1Q(A1:D15, F1, "C")

End Sub

You can also use macro functions contained in add-ins by using the Visual Basic ExecuteExcel4Macro method. This method takes as arguments the name and arguments of a macro function. For example, to use the ANOVA macro function to perform analysis of variance on data in the range A1:D15, include the following statement in your procedure:

Application.ExecuteExcel4Macro("ANOVA1?(A1:D15, F1,""C"")")

For more information on upgrading to Visual Basic, see Appendix B, "Switching from the Microsoft Excel 4.0 Macro Language," in the Microsoft Excel/Visual Basic for Windows 95 Programmer's Guide.


 Visual Basic Equivalents for Macro Functions and Commands

To see the Visual Basic statement that's equivalent to a Microsoft Excel 4.0 macro function, click the first letter of the function name. Then scroll through the list to find the macro function you're interested in.

More about converting Microsoft Excel version 4.0 macros to Visual Basic procedures


EnableAnimations Property

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.


EnableAnimations Property Example

This example turns off animated insertion and deletion.

Application.EnableAnimations = False


TemplatesPath Property

Returns the local path where templates are stored. This property is available only in Microsoft Excel for Windows 95. Read-only.


TemplatesPath Property Example

This example returns the path where templates are stored.

Msgbox Application.TemplatesPath


NetworkTemplatesPath Property

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.


NetworkTemplatesPath Property Example

This example displays the network path where templates are stored.

Msgbox Application.NetworkTemplatesPath


OnSave Property

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.


OnSave Property 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


EnableAutoComplete Property

True if the AutoComplete feature is enabled. This property is available only in Microsoft Excel for Windows 95. Read-write.


EnableAutoComplete Property Example

This example enables the AutoComplete feature.

Application.EnableAutoComplete = True


AutoComplete Method

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.


AutoComplete Method 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


MoveAfterReturnDirection Property

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.


MoveAfterReturnDirection Property Example

This example causes the active cell to move to the right when the user presses ENTER.

Application.MoveAfterReturn = True

Application.MoveAfterReturnDirection = xlToRight


AutoLoad Property

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.


AutoLoad Property Example

This example sets the AutoLoad property for OLE object one.

ActiveSheet.OLEObjects(1).AutoLoad = True


ListHeaderRows Property

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.


ListHeaderRows Property 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


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. 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.


RangeSelection Property Example

This example displays the address of the selected cells on the worksheet in the active window.

MsgBox ActiveWindow.RangeSelection.Address


SetBackgroundPicture Method

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.


SetBackgroundPicture Method Example

This example sets the background graphic for worksheet one.

Worksheets(1).SetBackgroundPicture "c:\graphics\watrmark.bmp"


Protection Property

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.


Protection Property 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


Container Property

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.


Container Property 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


Post Method

Posts the specified workbook to a public folder. This method is available only in Microsoft Excel for Windows 95 and works only with a Microsoft Exchange client connected to a Microsoft Exchange server.

Syntax

object.Post(destName)

object

Required. The workbook to post.

destName

Optional. Specifies the name of the destination public folder. In Microsoft Excel for Windows 95, this argument is ignored. The Post method prompts the user to specify the destination for the workbook.


Post Method Example

This example posts the active workbook.

ActiveWorkbook.Post


ProtectionMode Property

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.


ProtectionMode Property Example

This example displays the state of the ProtectionMode property.

MsgBox ActiveSheet.ProtectionMode


comparison operator <definition>
comparison operator

A character or symbol indicating a relationship between two or more values or expressions:

Symbol	Description

<	Less than

<=	Less than or equal to

> 	Greater than

>=	Greater than or equal to

<> 	Not equal

=	Equal

Additional comparison operators include Is and Like.  Note, however, that Is and Like can't be used as comparison operators in a Select Case statement.


constant <definition>
 constant

A named item that retains a constant value throughout the execution of a program, as opposed to a variable, whose value can change during execution.  Each application can predefine its own set of constants.  Additional constants may be defined using the Const statement.  Constants of either type can be used anywhere in your code in place of actual values.  A constant may be a string or numeric literal, another constant, or any combination that includes arithmetic or logical operators except Is.  For example:

Const A = "MyString"


data type <definition>
data type

The characteristic of a variable that determines what kind of data it can hold.  Data types include Boolean, Integer, Long, Currency, Single, Double, Date, String, Object, Variant (default) and user-defined types, as well as specific types of objects.

User-defined types are defined using the Type statement.  Arrays of user-defined and other data types are created using the Dim statement.  Arrays of any type can be included within user-defined types.


expression <definition>
expression

A combination of keywords, operators, variables, and constants that yield a string, number, or object.  An expression can perform a calculation, manipulate characters, or test data.


keyword <definition>
keyword

A word or symbol recognized as part of the programming language; for example, a statement, function name, or operator.

There are two types of keywords:

Type	Description

Restricted	Keywords that should not be used to name procedures.

Unrestricted	Keywords that can be used without restriction.  Many of the unrestricted keywords are system or application-provided functions, methods, properties, and statement names that are unknown to the compiler. This allows you to define your own procedures with the same name. For example, if you create a FileCopy procedure and call it from within your application, your version of FileCopy is used, rather than the system-provided FileCopy statement.


named argument <definition>
named argument

An argument that has a predefined name.  Instead of providing values for arguments in the order expected by the syntax, you can use named arguments to assign values in any order to only the arguments you want (if they are optional).  For example, suppose a method accepts three arguments:

DoSomeThing namedarg1, namedarg2, namedarg3

By assigning values to named arguments, you can use the following statement:

DoSomeThing namedarg3:=4,namedarg2:=5

Note that the arguments need not be in their normal positional order.


procedure level <definition>
procedure level

Statements located within a Function, Property, or Sub procedure.  Declarations are usually listed first, followed by assignments and other executable code.  For example:

Sub MySub()

Dim A	' This statement is a declaration.

A = "My variable"	' This statement is an assignment.

Debug.Print A	' This statement is executable.

End Sub

Note   In contrast, module-level code resides outside of any Sub...End Sub blocks.


scope <definition>
scope

Defines the accessibility and lifetime of a variable, procedure, or object.  For example, a variable declared as Public is available to all procedures in all modules in all applications (unless Option Private Module is in effect).


variable <definition>
variable

A named storage location that can contain a certain type of data that can be modified during program execution.  Each variable has a unique name that identifies it within its level of scope.  Variable names must begin with an alphabetic character, can't contain an embedded period or type-declaration character, and must be unique within the same scope.