Manual de Referencia VBA Excel

April 19, 2017 | Author: Rosalinda Hernandez Sanchez | Category: N/A
Share Embed Donate


Short Description

Download Manual de Referencia VBA Excel...

Description

Aplicaciones y Objetos

Application Workbooks Sheets WorkSheets Range Windows Cells Columns Rows

Collections Comments Workbooks WorkSheets Ranges Sheets

Objects Application Workbook Sheets WorkSheet Range Areas Comment

Application Objeto Represents the entire Microsoft Excel application.

Remarks The Application object contains:  Application-wide settings and options.  Methods that return top-level objects, such as ActiveCell, ActiveSheet, and so on.

Example Use the Application property to return the Application object. The following example applies the Windows property to the Application object. Application.Windows("book1.xls").Activate

The following example creates a Microsoft Excel workbook object in another application and then opens a workbook in Microsoft Excel. Set xl = CreateObject("Excel.Sheet") xl.Application.Workbooks.Open "newbook.xls"

Many of the properties and methods that return the most common userinterface 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

Events Name

Description

AfterCalculate

The AfterCalculate event occurs when all pending refresh activity (both synchronous and asynchronous) and all of the resultant calculation activities have been completed.

NewWorkbook

Occurs when a new workbook is created.

ProtectedViewWindowActivate

Occurs when a Protected View window is activated.

ProtectedViewWindowBeforeClose

Occurs immediately before a Protected View window or a workbook in aProtected View window closes.

ProtectedViewWindowBeforeEdit

Occurs immediately before editing is enabled on the workbook in the specifiedProtected View window.

ProtectedViewWindowDeactivate

Occurs when a Protected View window is deactivated.

ProtectedViewWindowOpen

Occurs when a workbook is opened in a Protected View window.

ProtectedViewWindowResize

Occurs when any View window is resized.

SheetActivate SheetBeforeDelete

SheetBeforeDoubleClick

Occurs when any worksheet is doubleclicked, before the default double-click action.

SheetBeforeRightClick

Occurs when any worksheet is rightclicked, before the default right-click action.

SheetCalculate

Occurs after any worksheet is recalculated or after any changed data is plotted on a chart.

SheetChange

Occurs when cells in any worksheet are changed by the user or by an external link.

SheetDeactivate

Occurs when any sheet is deactivated.

SheetFollowHyperlink

Occurs when you click any hyperlink in Microsoft Excel. For worksheet-level events, see the Help topic for the FollowHyperlink event.

SheetLensGalleryRenderComplete

Occurs after a callout gallery’s icons (dynamic & static) have finished rendering.

SheetPivotTableAfterValueChange

Occurs after a cell or range of cells inside a PivotTable are edited or recalculated (for cells that contain formulas).

SheetPivotTableBeforeAllocateChanges

Occurs before changes are applied to a PivotTable.

SheetPivotTableBeforeCommitChanges

Occurs before changes are committed against the OLAP data source for a PivotTable.

Protected

Occurs when any sheet is activated.

SheetPivotTableBeforeDiscardChanges

Occurs before changes to a PivotTable are discarded.

SheetPivotTableUpdate

Occurs after the sheet of the PivotTable report has been updated.

WorkbookBeforeClose

Occurs immediately before any open workbook closes.

SheetSelectionChange

Occurs when the selection changes on any worksheet (doesn't occur if the selection is on a chart sheet).

WorkbookBeforePrint

Occurs before any open workbook is printed.

WorkbookBeforeSave SheetTableUpdate

Occurs when a table on a worksheet is updated.

Occurs before any open workbook is saved.

WorkbookBeforeXmlExport WindowActivate

Occurs when any workbook window is activated.

Occurs before Microsoft Excel saves or exports XML data from the specified workbook.

WindowDeactivate

Occurs when any workbook window is deactivated.

WorkbookBeforeXmlImport

WindowResize

Occurs when any workbook window is resized.

Occurs before an existing XML data connection is refreshed, or new XML data is imported into any open Microsoft Excel workbook.

WorkbookDeactivate

Occurs when any open workbook is deactivated.

WorkbookModelChange

Occurs when the data model is updated.

WorkbookNewChart

Occurs when a new chart is created in any open workbook.

WorkbookNewSheet

Occurs when a new sheet is created in any open workbook.

WorkbookOpen

Occurs when a workbook is opened.

WorkbookPivotTableCloseConnection

Occurs after a PivotTable connection has been closed.

report

WorkbookPivotTableOpenConnection

Occurs after a PivotTable connection has been opened.

report

WorkbookActivate

Occurs when any workbook is activated.

WorkbookAddinInstall

Occurs when a workbook is installed as an add-in.

WorkbookAddinUninstall

Occurs when any add-in workbook is uninstalled.

WorkbookAfterSave

Occurs after the workbook is saved.

WorkbookAfterXmlExport

Occurs after Microsoft Excel saves or exports XML data from the specified workbook.

WorkbookAfterXmlImport

Occurs after an existing XML data connection is refreshed, or new XML

data is imported into Microsoft Excel workbook.

any

open

Methods Name

Description

ActivateMicrosoftApp

Activates a Microsoft application. If the application is already running, this method activates the running application. If the application isn't running, this method starts a new instance of the application.

AddCustomList

Adds a custom list for custom autofill and/or custom sort.

Calculate

Calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells on a worksheet, as shown in the following table.

CalculateFull

CalculateFullRebuild

CentimetersToPoints

Forces a full calculation of the data in all open workbooks. For all open workbooks, forces a full calculation of the data and rebuilds the dependencies. Converts a measurement from centimeters to points (one point equals 0.035 centimeters).

DisplayXMLSourcePane

Opens the XML Source task pane and displays the XML map specified by theXmlMap argument.

DoubleClick

Equivalent to double-clicking the active cell.

Evaluate

Converts a Microsoft Excel name to an object or a value.

FindFile

Displays the Open dialog box.

GetCustomListContents

Returns a custom list (an array of strings).

GetCustomListNum

Returns the custom list number for an array of strings. You can use this method to match both built-in lists and customdefined lists.

GetOpenFilename

Displays the standard Open dialog box and gets a file name from the user without actually opening any files.

GetSaveAsFilename

Displays the standard Save As dialog box and gets a file name from the user without actually saving any files.

Goto

Selects any range or Visual Basic procedure in any workbook, and activates that workbook if it’s not already active.

CheckAbort

Stops recalculation in a Microsoft Excel application.

ConvertFormula

Converts cell references in a formula between the A1 and R1C1 reference styles, between relative and absolute references, or both. Variant.

Help

Displays a Help topic.

InchesToPoints

Converts a measurement from inches to points.

Deletes a custom list.

InputBox

Displays a dialog box for user input. Returns the information entered in the dialog box.

DeleteCustomList

Intersect

MacroOptions

Returns a Range object that represents the rectangular intersection of two or more ranges.

SendKeys

Sends keystrokes to the active application.

Undo

Cancels the last user-interface action.

Corresponds to options in the Macro Options dialog box. You can also use this method to display a user defined function (UDF) in a built-in or new category within the Insert Function dialog box.

Union

Returns the union of two or more ranges.

Volatile

Marks a user-defined function as volatile. A volatile function must be recalculated whenever calculation occurs in any cells on the worksheet. A nonvolatile function is recalculated only when the input variables change. This method has no effect if it's not inside a user-defined function used to calculate a worksheet cell.

Wait

Pauses a running macro until a specified time. Returns True if the specified time has arrived.

OnKey

Runs a specified procedure when a particular key or key combination is pressed.

OnRepeat

Sets the Repeat item and the name of the procedure that will run if you choose theRepeat command after running the procedure that sets this property.

OnTime

Schedules a procedure to be run at a specified time in the future (either at a specific time of day or after a specific amount of time has passed).

OnUndo

Sets the text of the Undo command and the name of the procedure that’s run if you choose the Undo command after running the procedure that sets this property.

Quit

Quits Microsoft Excel.

RecordMacro

Records code if the macro recorder is on.

Repeat

Repeats the last user-interface action.

Run

Runs a macro or calls a function. This can be used to run a macro written in Visual Basic or the Microsoft Excel macro language, or to run a function in a DLL or XLL.

Properties Name

Description

ActiveCell

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 isn't displaying a worksheet, this property fails. Read-only.

ActiveChart

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's either selected or activated. When no chart is active, this property returnsNothing.

ActiveEncryptionSession

Returns a Long that represents the encryption session associated with the active document. Read-only.

ActivePrinter

Returns or sets the name of the active printer. Read/write String.

ActiveProtectedViewWindow

Returns a ProtectedViewWindow object that represents the activeProtected View window (the window on top). Read-only. Returns Nothingif there are no Protected View windows open. Read-only

ActiveSheet

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.

ActiveWindow

Returns a Window object that represents the active window (the window on top). Readonly. Returns Nothing if there are no windows open.

ActiveWorkbook

Returns a Workbook object that represents the workbook in the active window (the window on top). Read-only. Returns Nothing if there are no windows open or if either the Info window or the Clipboard window is the active window.

AddIns

Returns an AddIns collection that represents all the add-ins listed in theAdd-Ins dialog box (Add-Ins command on the Developer tab). Read-only.

AddIns2

Returns an AddIns2 collection that represents all the add-ins that are currently available or open in Microsoft Excel, regardless of whether they are installed. Read-only

AlertBeforeOverwriting

True if Microsoft Excel displays a message before overwriting nonblank cells during a drag-and-drop editing operation. Read/write Boolean.

AltStartupPath

Returns or sets the name of the alternate startup folder. Read/write String.

AlwaysUseClearType

Returns or sets a Boolean that represents whether to use ClearType to display fonts in the menu, ribbon, and dialog box text. Read/write Boolean.

Application

When used without an object qualifier, this property returns an Applicationobject that represents the Microsoft Excel application. When 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 application of that object). Read-only.

ArbitraryXMLSupportAvailable

Returns a Boolean value that indicates whether the XML features in Microsoft Excel are available. Read-only.

CellDragAndDrop

True if dragging and dropping cells is enabled. Read/write Boolean.

AskToUpdateLinks

True if Microsoft Excel asks the user to update links when opening files with links. False if links are automatically updated with no dialog box. Read/writeBoolean.

Cells

Returns a Range object that represents all the cells on the active worksheet. If the active document is not a worksheet, this property fails.

AutoCorrect

Returns an AutoCorrect object that represents the Microsoft Excel AutoCorrect attributes. Read-only.

ChartDataPointTrack

True will cause all charts in newly created documents to use the cell reference tracking behavior.Boolean

AutomationSecurity

Returns or sets an MsoAutomationSecurity constant that represents the security mode Microsoft Excel uses when programmatically opening files. Read/write.

Charts

Returns a Sheets collection that represents all the chart sheets in the active workbook.

Columns

Returns a Range object that represents all the columns on the active worksheet. If the active document isn't a worksheet, the Columns property fails.

True if entries in cells formatted as percentages aren’t automatically multiplied by 100 as soon as they are entered. Read/write Boolean.

COMAddIns

Returns the COMAddIns collection for Microsoft Excel, which represents the currently installed COM add-ins. Read-only.

AutoRecover

Returns an AutoRecover object, which backs up all file formats on a timed interval.

CommandBars

Returns a CommandBars object that represents the Microsoft Excel command bars. Read-only.

CalculateBeforeSave

True if workbooks are calculated before they're saved to disk (if theCalculation property is set to xlManual). This property is preserved even if you change the Calculation property. Read/write Boolean.

ConstrainNumeric

True if handwriting recognition is limited to numbers and punctuation only. Read/write Boolean.

ControlCharacters

True if Microsoft Excel displays control characters for right-to-left languages. Read/write Boolean.

CopyObjectsWithCells

True if objects are cut, copied, extracted, and sorted with cells. Read/writeBoolean.

AutoPercentEntry

Calculation

Returns or sets a XlCalculation value that represents the calculation mode.

Caption

Returns or sets a String value that represents the name that appears in the title bar of the main Microsoft Excel window.

Cursor

Returns or sets the appearance of the mouse pointer in Microsoft Excel. Read/write XlMousePointer.

CustomListCount

Returns the number of defined custom lists (including built-in lists). Read-only Long.

CutCopyMode

DataEntryMode

DecimalSeparator

DefaultFilePath

Returns or sets the status of Cut or Copy mode. Can be True, False, or anXLCutCopyMode constant, as shown in the following tables. Read/writeLong. 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 in the currently selected range. Read/write Long. Sets or returns the character used for the decimal separator as a String. Read/write. Returns or sets the default path that Microsoft Excel uses when it opens files. Read/write String.

DisplayDocumentActionTaskPane

Set to True to display the Document Actions task pane; set to False to hide the Document Actions task pane. Read/write Boolean.

DisplayDocumentInformationPanel

Returns or sets a Boolean that represents whether the document properties panel is displayed. Read/write Boolean.

DisplayFormulaAutoComplete

Gets or sets whether to show a list of relevant functions and defined names when building cell formulas. Read/write Boolean.

DisplayFormulaBar

True if the formula bar is displayed. Read/write Boolean.

DisplayFullScreen

True if Microsoft Excel is in full-screen mode. Read/write Boolean.

DisplayFunctionToolTips

True if function ToolTips can be displayed. Read/write Boolean.

DisplayInsertOptions

True if the Insert Options button should be displayed. Read/write Boolean.

DefaultSaveFormat

Returns or sets the default format for saving files. For a list of valid constants, see the FileFormat property. Read/write Long.

DisplayNoteIndicator

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

DisplayAlerts

True if Microsoft Excel displays certain alerts and messages while a macro is running. Read/write Boolean.

DisplayPasteOptions

True if the Paste Options button can be displayed. Read/write Boolean.

DisplayClipboardWindow

Returns True if the Microsoft Office Clipboard can be displayed. Read/writeBoolean.

DisplayRecentFiles

True if the list of recently used files is displayed in the UI. Read/writeBoolean.

DisplayCommentIndicator

Returns or sets the way cells display comments and indicators. Can be one of the XlCommentDisplayMode constants.

DisplayScrollBars

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

DisplayStatusBar

True if the status bar is displayed. Read/write Boolean.

FileValidation

Returns or sets how Excel will validate files before opening them. Read/write

EditDirectlyInCell

True if Microsoft Excel allows editing in cells. Read/write Boolean.

FileValidationPivot

Returns or sets how Excel will validate the contents of the data caches for PivotTable reports. Read/write

EnableAutoComplete

True if the AutoComplete feature is enabled. Read/write Boolean.

FindFormat

Sets or returns the search criteria for the type of cell formats to find.

FixedDecimal

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. Read/write Boolean.

FixedDecimalPlaces

Returns or sets the number of fixed decimal places used when theFixedDecimal property is set to True. Read/write Long.

FormulaBarHeight

Allows the user to specify the height of the formula bar in lines. Read/writeLong.

GenerateGetPivotData

Returns True when Microsoft Excel can get PivotTable report data. Read/write Boolean.

GenerateTableRefs

The GenerateTableRefs property determines whether the traditional notation method or the new structured referencing notation method is used for referencing tables in formulas. Read/write.

EnableCancelKey

Controls how Microsoft Excel handles CTRL+BREAK (or ESC or COMMAND+PERIOD) user interruptions to the running procedure. Read/write XlEnableCancelKey.

EnableCheckFileExtensions EnableEvents

True if events are enabled for the specified object. Read/write Boolean.

ErrorCheckingOptions

Returns an ErrorCheckingOptions object, which represents the error checking options for an application.

ExtendList

True if Microsoft Excel automatically extends formatting and formulas to new data that is added to a list. Read/write Boolean.

FileConverters

Returns information about installed file converters. Returns null if there are no converters installed. Read-only Variant.

FileDialog

Returns a FileDialog object representing an instance of the file dialog.

Height

FileExportConverters

Returns a FileExportConverters collection that represents all the file converters for saving files available to Microsoft Excel. Readonly.

Returns or sets a Double value that represents tThe height, in points, of the main application window.

Interactive

True if Microsoft Excel is in interactive mode; this property is usually True. If you set the this property to False, Microsoft Excel will block all input from the keyboard and mouse (except

input to dialog boxes that are displayed by your code). Read/write Boolean. International

MouseAvailable

True if a mouse is available. Readonly Boolean.

MoveAfterReturn

True if the active cell will be moved as soon as the ENTER (RETURN) key is pressed. Read/write Boolean.

MoveAfterReturnDirection

Returns or sets the direction in which the active cell is moved when the user presses ENTER. Read/write XlDirection.

MultiThreadedCalculation

Returns a MultiThreadedCalculation object that controls the multi-threaded recalculation settings. Read-only.

Name

Returns a String value that represents the name of the object.

Names

True if documents formatted for the standard paper size of another country/region (for example, A4) are automatically adjusted so that they're printed correctly on the standard paper size (for example, Letter) of your country/region. Read/write Boolean.

Returns a Names collection that represents all the names in the active workbook. Readonly Names object.

NewWorkbook

Returns a NewFile object.

OnWindow

Returns or sets the maximum amount of change between each iteration as Microsoft Excel resolves circular references. Read/write Double.

Returns or sets the name of the procedure that’s run whenever you activate a window. Read/write String.

Parent

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

Path

Returns a String value that represents the complete path to the application, excluding the final separator and name of the application.

Returns information about the current country/region and international settings. Read-only Variant.

IsSandboxed

Returns True if the specified workbook is open in a Protected Viewwindow. Read-only

Iteration

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

Left

Returns or sets a Double value that represents the distance, in points, from the left edge of the screen to the left edge of the main Microsoft Excel window.

LibraryPath

MapPaperSize

MaxChange

MergeInstances

Returns the path to the Library folder, but without the final separator. Read-only String.

MaxIterations

Returns or sets the maximum number of iterations that Microsoft Excel can use to resolve a circular reference. Read/write Long.

MeasurementUnit

Specifies the measurement unit used in the application. Read/writexlMeasurementUnit.

PathSeparator

Returns the path separator character ("\"). Read-only String.

PivotTableSelection

True if PivotTable reports use structured selection. Read/write Boolean.

PreviousSelections

Returns an array of the last four ranges or names selected. Each element in the array is a Range object. Read-only Variant.

PrintCommunication

Specifies whether communication with the printer is turned on. BooleanRead/write

PromptForSummaryInfo

True if Microsoft Excel asks for summary information when files are first saved. Read/write Boolean.

ProtectedViewWindows

QuickAnalysis

Range

Ready

RecentFiles

RecordRelative

Returns a ProtectedViewWindows collection that represents all theProtected View windows that are open in the application. Read-only Returns a QuickAnalysis object that represents the Quick Analysis options of the application. Returns a Range object that represents a cell or a range of cells. Returns True when the Microsoft Excel application is ready; False when the Excel application is not ready. Read-only Boolean. Returns a RecentFiles collection that represents the list of recently used files. True if macros are recorded using relative references; False if recording is absolute. Read-only Boolean.

ReferenceStyle

Returns or sets how Microsoft Excel displays cell references and row and column headings in either A1 or R1C1 reference style. Read/writeXlReferenceStyle.

RegisteredFunctions

Returns information about functions in either dynamic-link libraries (DLLs) or code resources that were registered with the REGISTER or REGISTER.ID macro functions. Readonly Variant.

ReplaceFormat

Sets the replacement criteria to use in replacing cell formats. The replacement criteria is then used in a subsequent call to the Replace method of the Range object.

RollZoom

True if the IntelliMouse zooms instead of scrolling. Read/write Boolean.

Rows

Returns a Range object that represents all the rows on the active worksheet. If the active document isn’t a worksheet, the Rows property fails. ReadonlyRange object.

ScreenUpdating

True if screen updating is turned on. Read/write Boolean.

Selection

Returns the selected object in the active window for an Application object.

Sheets

Returns a Sheets collection that represents all the sheets in the active workbook. Readonly Sheets object.

SheetsInNewWorkbook

Returns or sets the number of sheets that Microsoft Excel automatically inserts into new workbooks. Read/write Long.

ShowChartTipNames

True if charts show chart tip names. The default value is True. Read/writeBoolean.

SmartArtLayouts

Returns the set of SmartArt layouts that are currently loaded in the application. Read-only

ShowChartTipValues

True if charts show chart tip values. The default value is True. Read/writeBoolean.

SmartArtQuickStyles

Returns the set of SmartArt quick styles which are currently loaded in the application. Readonly

ShowDevTools

Returns or sets a Boolean that represents whether the Developer tab is displayed in the ribbon. Read/write Boolean.

StandardFont

Returns or sets the name of the standard font. Read/write String.

StandardFontSize

Returns or sets the standard font size, in points. Read/write Long.

StartupPath

Returns the complete path of the startup folder, excluding the final separator. Readonly String.

StatusBar

Returns or sets the text in the status bar. Read/write String.

TemplatesPath

Returns the local path where templates are stored. Read-only String.

ThisCell

Returns or sets a Boolean that represents whether Mini toolbars displays when a user selects text. False if Mini toolbars are displayed. Read/writeBoolean.

Returns the cell in which the user-defined function is being called from as aRange object.

ThisWorkbook

Returns True (default is False) when the New Workbook task pane appears for a Microsoft Excel application. Read/write Boolean.

Returns a Workbook object that represents the workbook where the current macro code is running. Read-only.

ThousandsSeparator

Sets or returns the character used for the thousands separator as a String. Read/write.

ShowToolTips

True if ToolTips are turned on. Read/write Boolean.

Top

SmartArtColors

Returns the set of color styles that are currently loaded in the application. Read-only

Returns or sets a Double value that represents the distance, in points, from the top edge of the screen to the top edge of the main Microsoft Excel window.

ShowMenuFloaties

ShowQuickAnalysis

ShowSelectionFloaties

ShowStartupDialog

Returns or sets a Boolean that represents whether to display Mini toolbarswhen the user right-clicks in the workbook window. False if Mini toolbarsare displayed. Read/write Boolean. Controls whether the Quick Analysis contextual user interface is displayed on selection. TRUE means the Quick Analysis button will show. Corresponds to the Show Quick Analysis options on selection checkbox located in theFile menu, Options, Excel Options, and then General tab. Read/Write.Boolean.

TransitionMenuKey

Returns or sets the Microsoft Excel menu or help key, which is usually "/". Read/write String.

Visible

Returns or sets a Boolean value that determines whether the object is visible. Read/write.

TransitionNavigKeys

True if transition navigation keys are active. Read/write Boolean.

WarnOnFunctionNameConflict

UsableHeight

Returns the maximum height of the space that a window can occupy in the application window area, in points. Read-only Double.

The WarnOnFunctionNameConflict property , when set to True, raises an alert if a developer tries to create a new function using an existing function name. Read/write Boolean.

Watches

Returns a Watches object representing a range which is tracked when the worksheet is recalculated.

Width

Returns or sets a Double value that represents the distance, in points, from the left edge of the application window to its right edge.

UsableWidth

Returns the maximum width of the space that a window can occupy in the application window area, in points. Read-only Double.

UsedObjects

Returns a UsedObjects object representing objects allocated in a workbook. Read-only

UserControl

True if the application is visible or if it was created or started by the user.False if you created or started the application programmatically by using theCreateObject or GetObject functions, and the application is hidden. Read/write Boolean.

Windows

Returns a Windows collection that represents all the windows in all the workbooks. Readonly Windows object.

WindowState

Returns or sets the state of the window. Read/write XlWindowState.

UserLibraryPath

Returns the path to the location on the user’s computer where the COM add-ins are installed. Read-only String.

Workbooks

Returns a Workbooks collection that represents all the open workbooks. Read-only.

WorksheetFunction UserName

Returns or sets the name of the current user. Read/write String.

Returns the WorksheetFunction object. Read-only.

Worksheets UseSystemSeparators

True (default) if the system separators of Microsoft Excel are enabled. Read/write Boolean.

Value

Returns a String value that represents the name of the application.

For an Application object, returns a Sheets collection that represents all the worksheets in the active workbook. For a Workbook object, returns aSheets collection that represents all the worksheets in the specified workbook. Readonly Sheets object.

Application. Workbooks Returns a Workbooks collection that represents all the open workbooks. Read-only.

Syntax expression .Workbooks expression A variable that represents an Application object.

Remarks Using this property without an object qualifier is equivalent to using Application.Workbooks . The collection returned by the Workbooks property doesn’t include open addins, which are a special kind of hidden workbook. You can, however, return a single open add-in if you know the file name. For example, Workbooks("Oscar.xla") will return the open add-in named "Oscar.xla" as a Workbook object.

A workbook displayed in a protected view window is not a member of the Workbooks collection. Instead, use theWorkbook property of the ProtectedViewWindow object to access a workbook that is displayed in a protected view window.

Example This example activates the workbook Book1.xls. Workbooks("BOOK1").Activate

This example opens the workbook Large.xls. Workbooks.Open filename:="LARGE.XLS"

T his example saves changes to and closes all workbooks except the one that’s running the example. For Each w In Workbooks If w.Name ThisWorkbook.Name Then w.Close savechanges:=True End If Next w

Use the Workbooks property to return the Workbooks collection. The following example closes all open workbooks. Workbooks.Close

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.

Methods Name

Description

Add

Creates a new workbook. The new workbook becomes the active workbook.

CanCheckOut

True if Microsoft Excel can check out a specified workbook from a server. Read/write Boolean.

CheckOut

Returns a String representing a specified workbook from a server to a local computer for editing.

Close

Closes the object.

Open

Opens a workbook.

OpenDatabase

Returns a Workbook object representing a database.

OpenText

Loads and parses a text file as a new workbook with a single sheet that contains the parsed text-file data.

OpenXML

Opens an XML data file. Returns a Workbook object.

Workbooks.Add

Use the Open method to open a file. This creates a new workbook for the opened file. The following example opens the file Array.xls as a read-only workbook. Workbooks.Open FileName:="Array.xls", ReadOnly:=True

Properties Name

Description

Application

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When used with an object qualifier, this property returns an Applicationobject that represents the creator of the specified object (you can use this property with an OLE Automation object to return the application of that object). Read-only.

Count

Returns a Long value that represents the number of objects in the collection.

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Readonly Long.

Item

Returns a single object from a collection.

Parent

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

Workbooks Object A collection of all the Workbook objects that are currently open in the Microsoft Excel application.

Remarks For more information about using a single Workbook object, see the Workbook object.

Example Use the Workbooks property to return the Workbooks collection. The following example closes all open workbooks. Workbooks.Close

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. Workbooks.Add

Use the Open method to open a file. This creates a new workbook for the opened file. The following example opens the file Array.xls as a read-only workbook. Workbooks.Open FileName:="Array.xls", ReadOnly:=True

Methods

Properties

Name

Description

Name

Description

Add

Creates a new workbook. The new workbook becomes the active workbook.

Application

CanCheckOut

True if Microsoft Excel can check out a specified workbook from a server. Read/write Boolean.

CheckOut

Returns a String representing a specified workbook from a server to a local computer for editing.

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When used with an object qualifier, this property returns an Applicationobject that represents the creator of the specified object (you can use this property with an OLE Automation object to return the application of that object). Read-only.

Count

Returns a Long value that represents the number of objects in the collection.

Close

Closes the object.

Open

Opens a workbook.

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.

OpenDatabase

Returns a Workbook object representing a database.

Item

Returns a single object from a collection.

OpenText

Loads and parses a text file as a new workbook with a single sheet that contains the parsed text-file data.

Parent

Returns the parent object for the specified object. Readonly.

OpenXML

Opens an XML data file. Returns a Workbook object.

Workbook Object Represents a Microsoft Excel workbook.

Remarks The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel.

ThisWorkbook Property 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 ThisWorkbookproperty won’t return the active workbook. In this case, the active workbook is the workbook calling the add-in, whereas the ThisWorkbook property returns the add-in workbook. If you’ll be creating an add-in from your Visual Basic code, you should use the ThisWorkbook property to qualify any statement that must be run on the workbook you compile into the add-in.

Example Use Workbooks(index), where index is the workbook name or index number, to return a single Workbook object. The following example activates workbook one. Workbooks(1).Activate

The index number denotes the order in which the workbooks were opened or created. Workbooks(1) is the first workbook created, and Workbooks(Workbooks.Count) is the last one created. Activating a workbook doesn’t change its index number. All workbooks are included in the index count, even if they’re hidden.

The Name property returns the workbook name. You cannot set the name by using this property; if you need to change the name, use the SaveAs method to save the workbook under a different name. The following example activates Sheet1 in the workbook named Cogs.xls (the workbook must already be open in Microsoft Excel).

Events Name

Description

Activate

Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.

The ActiveWorkbook property returns the workbook that’s currently active. The following example sets the name of the author for the active workbook.

AddinInstall

Occurs when the workbook is installed as an add-in

ActiveWorkbook.Author = "Jean Selva"

AddinUninstall

Occurs when the workbook is uninstalled as an add-in.

AfterSave

Occurs after the workbook is saved.

AfterXmlExport

Occurs after Microsoft Excel saves or exports XML data from the specified workbook.

AfterXmlImport

Occurs after an existing XML data connection is refreshed or after new XML data is imported into the specified Microsoft Excel workbook.

BeforeClose

Occurs before the workbook closes. If the workbook has been changed, this event occurs before the user is asked to save changes.

BeforePrint

Occurs before the workbook (or anything in it) is printed.

BeforeSave

Occurs before the workbook is saved.

BeforeXmlExport

Occurs before Microsoft Excel saves or exports XML data from the specified workbook.

Workbooks("Cogs.xls").Worksheets("Sheet1").Activate

BeforeXmlImport

Occurs before an existing XML data connection is refreshed or before new XML data is imported into a Microsoft Excel workbook.

Deactivate

Occurs when the chart, worksheet, or workbook is deactivated.

ModelChange

Occurs after the Excel data model is changed.

NewChart

Occurs when a new chart is created in the workbook.

SheetBeforeRightClick

Occurs when any worksheet is rightclicked, before the default right-click action.

SheetCalculate

Occurs after any worksheet is recalculated or after any changed data is plotted on a chart.

SheetChange

Occurs when cells in any worksheet are changed by the user or by an external link.

SheetDeactivate

Occurs when any sheet is deactivated.

SheetFollowHyperlink

Occurs when you click any hyperlink in Microsoft Excel. For worksheet-level events, see the Help topic for the FollowHyperlink event.

SheetLensGalleryRenderComplete

Occurs when a callout gallery’s icons (dynamic & static) have completed rendering for a worksheet.

NewSheet

Occurs when a new sheet is created in the workbook.

Open

Occurs when the workbook is opened.

PivotTableCloseConnection

Occurs after a PivotTable report closes the connection to its data source.

PivotTableOpenConnection

Occurs after a PivotTable report opens the connection to its data source.

SheetPivotTableAfterValueChange

RowsetComplete

The event is raised when the user either drills through the recordset or invokes the rowset action on an OLAP PivotTable.

Occurs after a cell or range of cells inside a PivotTable are edited or recalculated (for cells that contain formulas).

SheetPivotTableBeforeAllocateChanges

Occurs before changes are applied to a PivotTable.

SheetPivotTableBeforeCommitChanges

Occurs before changes are committed against the OLAP data source for a PivotTable.

SheetPivotTableBeforeDiscardChanges

Occurs before changes to a PivotTable are discarded.

SheetPivotTableChangeSync

Occurs after changes to a PivotTable.

SheetActivate

Occurs when any sheet is activated.

SheetBeforeDelete SheetBeforeDoubleClick

Occurs when any worksheet is doubleclicked, before the default double-click action.

SheetPivotTableUpdate

Occurs after the sheet of the PivotTable report has been updated.

SheetSelectionChange

Occurs when the selection changes on any worksheet (doesn't occur if the selection is on a chart sheet).

SheetTableUpdate

Occurs after the sheet table has been updated.

Sync

This object or member has been deprecated, but it remains part of the object model for backward compatibility. You should not use it in new applications.

WindowActivate

Occurs when any workbook window is activated.

WindowDeactivate

Occurs when any workbook window is deactivated.

WindowResize

Occurs when any workbook window is resized.

Methods Name

Description

AcceptAllChanges

Accepts all changes in the specified shared workbook.

Activate

Activates the first window associated with the workbook.

AddToFavorites

Adds a shortcut to the workbook or hyperlink to the Favorites folder.

ApplyTheme

Applies the specified theme to the current workbook.

BreakLink

Converts formulas linked to other Microsoft Excel sources or OLE sources to values.

CanCheckIn

True if Microsoft Excel can check in a specified workbook to a server. Read/writeBoolean.

ChangeFileAccess

Changes the access permissions for the workbook. This may require an updated version to be loaded from the disk.

ChangeLink

Changes a link from one document to another.

CheckIn

Returns a workbook from a local computer to a server, and sets the local workbook to read-only so that it cannot be edited locally. Calling this method will also close the workbook.

CheckInWithVersion

Saves a workbook to a server from a local computer, and sets the local workbook to

read-only so that it cannot be edited locally.

GetWorkflowTemplates

Returns the collection of WorkflowTemplate objects for the specified workbook.

HighlightChangesOptions

Controls how changes are shown in a shared workbook.

LinkInfo

Returns the link date and update status.

LinkSources

Terminates a review of a file that has been sent for review using the SendForReviewmethod.

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.

LockServerFile

Locks the workbook on the server to prevent modification.

Assigns the current user exclusive access to the workbook that's open as a shared list.

MergeWorkbook

Merges changes from one workbook into an open workbook.

NewWindow

Creates a new window or a copy of the specified window.

OpenLinks

Opens the supporting documents for a link or links.

PivotCaches

Returns a PivotCaches collection that represents all the PivotTable caches in the specified workbook. Read-only.

Post

Posts the specified workbook to a public folder. This method works only with a Microsoft Exchange client connected to a Microsoft Exchange server.

PrintOut

Prints the object.

Close

Closes the object.

DeleteNumberFormat

Deletes a custom number format from the workbook.

EnableConnections

EndReview

ExclusiveAccess

ExportAsFixedFormat

FollowHyperlink

ForwardMailer

GetWorkflowTasks

The EnableConnections method allows developers to programmatically enable data connections within the workbook for the user.

The ExportAsFixedFormat method is used to publish a workbook to either the PDF or XPS format. Displays a cached document, if it’s already been downloaded. Otherwise, this method resolves the hyperlink, downloads the target document, and displays the document in the appropriate application. You have requested Help for a Visual Basic keyword used only on the Macintosh. For information about this keyword, consult the language reference Help included with Microsoft Office Macintosh Edition. Returns the collection of WorkflowTask objects for the specified workbook.

PrintPreview

Shows a preview of the object as it would look when printed.

review, notifying them that a reviewer has completed review of the workbook.

Protect

Protects a workbook so that it cannot be modified.

ResetColors

Resets the color palette to the default colors.

ProtectSharing

Saves the workbook and protects it for sharing.

RunAutoMacros

PurgeChangeHistoryNow

Removes entries from the change log for the specified workbook.

RefreshAll

Refreshes all external data ranges and PivotTable reports in the specified workbook.

Runs the Auto_Open, Auto_Close, Auto_Activate, or Auto_Deactivate macro attached to the workbook. This method is included for backward compatibility. For new Visual Basic code, you should use the Open, Close, Activate and Deactivate events instead of these macros.

Save

Saves changes to the specified workbook.

RejectAllChanges

Rejects all changes in the specified shared workbook.

SaveAs

Saves changes to the workbook in a different file.

RemoveDocumentInformation

Removes all information of the specified type from the workbook.

SaveAsXMLData

Exports the data that has been mapped to the specified XML schema map to an XML data file.

RemoveUser

Disconnects the specified user from the shared workbook.

SaveCopyAs

Reply

You have requested Help for a Visual Basic keyword used only on the Macintosh. For information about this keyword, consult the language reference Help included with Microsoft Office Macintosh Edition.

Saves a copy of the workbook to a file but doesn't modify the open workbook in memory.

SendFaxOverInternet

Sends a worksheet as a fax to the specfied recipients.

SendForReview

Sends a workbook in an e-mail message for review to the specified recipients.

SendMail

Sends the workbook by using the installed mail system.

SendMailer

You have requested Help for a Visual Basic keyword used only on the Macintosh. For information about this keyword, consult

ReplyAll

ReplyWithChanges

You have requested Help for a Visual Basic keyword used only on the Macintosh. For information about this keyword, consult the language reference Help included with Microsoft Office Macintosh Edition. Sends an e-mail message to the author of a workbook that has been sent out for

the language reference Help included with Microsoft Office Macintosh Edition. SetPasswordEncryptionOptions

Sets the options for encrypting workbooks using passwords.

ToggleFormsDesign

The ToggleFormsDesign method is used to toggle Excel into Design Mode when using forms controls.

Properties Name

Description

AccuracyVersion

Specifies whether certain worksheet functions use the latest accuracy algorithms to calculate their results. Read/write

ActiveChart

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's either selected or activated. When no chart is active, this property returns Nothing.

Unprotect

Removes protection from a sheet or workbook. This method has no effect if the sheet or workbook isn't protected.

UnprotectSharing

Turns off protection for sharing and saves the workbook.

ActiveSheet

UpdateFromFile

Updates a read-only workbook from the saved disk version of the workbook if the disk version is more recent than the copy of the workbook that is loaded in memory. If the disk copy hasn't changed since the workbook was loaded, the in-memory copy of the workbook isn't reloaded.

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.

ActiveSlicer

Returns an object that represents the active slicer in the active workbook or in the specified workbook. Returns Nothing if no slicer is active. Read-only.

UpdateLink

Updates a Microsoft Excel, DDE, or OLE link (or links).

Application

XmlImport

Imports an XML data file into the current workbook.

XmlImportXml

Imports an XML data stream that has been previously loaded into memory. Excel uses the first qualifying map found or if the destination range is specified, Excel will automatically list the data.

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When 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 application of that object). Read-only.

AutoUpdateFrequency

Returns or sets the number of minutes between automatic updates to the shared workbook. Read/write Long.

AutoUpdateSaveChanges

Colors

Returns or sets colors in the palette for the workbook. The palette has 56 entries, each represented by an RGB value. Read/write Variant.

CommandBars

Returns a CommandBars object that represents the Microsoft Excel command bars. Read-only.

Returns a DocumentProperties collection that represents all the built-in document properties for the specified workbook. Readonly.

ConflictResolution

Returns or sets the way conflicts are to be resolved whenever a shared workbook is updated. Read/write XlSaveConflictResolution.

Returns the information about the version of Excel that the workbook was last fully recalculated by. Read-only Long.

Connections

The Connections property establishes a connection between the workbook and an ODBC or an OLEDB data source and refreshes the data without prompting the user. Readonly.

ConnectionsDisabled

Disables the external connections or links in the workbook. Read-only

Container

True will cause all charts in the current document to track the actual data point to which it’s attached. False will revert back to tracking the index of the data point.Boolean Read/Write

Returns the object that represents the container application for the specified OLE object. Read-only Object.

ContentTypeProperties

Returns a MetaProperties collection that describes the metadata stored in the workbook. Read-only.

Charts

Returns a Sheets collection that represents all the chart sheets in the specified workbook.

CreateBackup

True if a backup file is created when this file is saved. Read-only Boolean.

CheckCompatibility

Controls whether or not the compatibility checker is run automatically when the workbook is saved. Read/write Boolean.

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.

CodeName

Returns the code name for the object. Readonly String.

CustomDocumentProperties

Returns or sets a DocumentProperties collection that

BuiltinDocumentProperties

CalculationVersion

True if current changes to the shared workbook are posted to other users whenever the workbook is automatically updated. False if changes aren’t posted (this workbook is still synchronized with changes made by other users). The default value is True. Read/write Boolean.

CaseSensitive

True if the workbook distinguishes between upper and lower case when comparing content. Read-only Boolean

ChangeHistoryDuration

Returns or sets the number of days shown in the shared workbook's change history. Read/write Long.

ChartDataPointTrack

represents all the custom document properties for the specified workbook. CustomViews

Returns a CustomViews collection that represents all the custom views for the workbook.

CustomXMLParts

Returns a CustomXMLParts collection that represents the custom XML in the XML data store. Read-only.

Date1904

True if the workbook uses the 1904 date system. Read/write Boolean.

DefaultPivotTableStyle

Specifies the table style from the TableStyles collection that is used as the default style for PivotTables. Read/write.

DefaultSlicerStyle

Specifies the style from the TableStyles object that is used as the default style for slicers. Read/write.

DefaultTableStyle

Specifies the table style from the TableStyles collection that is used as the default TableStyle. Read/write Variant.

DefaultTimelineStyle

The name of the default slicer style of the workbook. Variant. Read/Write

DisplayDrawingObjects

Returns or sets how shapes are displayed. Read/write Long.

DisplayInkComments

A Boolean value that determines whether ink comments are displayed in the workbook. Read/write Boolean.

DocumentInspectors

Returns a DocumentInspectors collection that represents the Document Inspector

modules for the specified workbook. Readonly. DocumentLibraryVersions

Returns a DocumentLibraryVersions collection that represents the collection of versions of a shared workbook that has versioning enabled and that is stored in a document library on a server.

DoNotPromptForConvert

Returns or sets if the user should be prompted to convert the workbook if the workbook contains features that are not supported by versions of Excel earlier than Excel 2007. Read/write Boolean.

EnableAutoRecover

Saves changed files, of all formats, on a timed interval. Read/write Boolean.

EncryptionProvider

Returns a String specifying the name of the algorithm encryption provider that Microsoft Office Excel 2007 uses when encrypting documents. Read/write.

EnvelopeVisible

True if the e-mail composition header and the envelope toolbar are both visible. Read/write Boolean.

Excel4IntlMacroSheets

Returns a Sheets collection that represents all the Microsoft Excel 4.0 international macro sheets in the specified workbook. Read-only.

Excel4MacroSheets

Returns a Sheets collection that represents all the Microsoft Excel 4.0 macro sheets in the specified workbook. Read-only.

Excel8CompatibilityMode

The Excel8CompatibilityMode property provides developers with a way to check if the workbook is in compatibility mode. Readonly Boolean.

FileFormat

Returns the file format and/or type of the workbook. Read-only XlFileFormat.

Final

ForceFullCalculation

FullName

IsInplace

Returns or sets a Boolean that indicates whether a workbook is final. Read/writeBoolean.

True if the specified workbook is being edited in place. False if the workbook has been opened in Microsoft Excel for editing. Readonly Boolean.

KeepChangeHistory

True if change tracking is enabled for the shared workbook. Read/write Boolean.

Returns or sets the specified workbook to forced calculation mode. Read/write.

ListChangesOnNewSheet

True if changes to the shared workbook are shown on a separate worksheet. Read/write Boolean.

Mailer

You have requested Help for a Visual Basic keyword used only on the Macintosh. For information about this keyword, consult the language reference Help included with Microsoft Office Macintosh Edition.

Returns the name of the object, including its path on disk, as a string. Read-onlyString.

FullNameURLEncoded

Returns a String indicating the name of the object, including its path on disk, as a string. Read-only.

HasPassword

True if the workbook has a protection password. Read-only Boolean.

Model

HasVBProject

Returns a Boolean that represents whether a workbook has an attached Microsoft Visual Basic for Applications project. Readonly Boolean.

Returns the top level Model object which is the one Data Model for the workbook. Readonly

MultiUserEditing

True if the workbook is open as a shared list. Read-only Boolean.

HighlightChangesOnScreen

True if changes to the shared workbook are highlighted on-screen. Read/writeBoolean.

Name

Returns a String value that represents the name of the object.

IconSets

This property is used to filter data in a workbook based on a cell icon from theIconSet collection. Read-only.

Names

Returns a Names collection that represents all the names in the specified workbook (including all worksheet-specific names). Read-only Names object.

InactiveListBorderVisible

A Boolean value that specifies whether list borders are visible when a list is not active. Returns True if the border is visible. Read/write Boolean.

Parent

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

Password

Returns or sets the password that must be supplied to open the specified workbook. Read/write String.

IsAddin

True if the workbook is running as an add-in. Read/write Boolean.

PasswordEncryptionAlgorithm

Returns a String indicating the algorithm Microsoft Excel uses to encrypt passwords for the specified workbook. Read-only.

PrecisionAsDisplayed

True if calculations in this workbook will be done using only the precision of the numbers as they’re displayed. Read/write Boolean.

PasswordEncryptionFileProperties

True if Microsoft Excel encrypts file properties for the specified password-protected workbook. Read-only Boolean.

ProtectStructure

True if the order of the sheets in the workbook is protected. Read-only Boolean.

ProtectWindows PasswordEncryptionKeyLength

Returns a Long indicating the key length of the algorithm Microsoft Excel uses when encrypting passwords for the specified workbook. Read-only.

True if the windows of the workbook are protected. Read-only Boolean.

PublishObjects

Returns the PublishObjects collection. Readonly.

ReadOnly

Returns True if the object has been opened as read-only. Read-only Boolean.

ReadOnlyRecommended

True if the workbook was saved as read-only recommended. Read-only Boolean.

RemovePersonalInformation

True if personal information can be removed from the specified workbook. The default value is False. Read/write Boolean.

Research

Returns a Research object that represents the research service for a workbook. Read-only.

RevisionNumber

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). Read-only Long.

Saved

True if no changes have been made to the specified workbook since it was last saved. Read/write Boolean.

SaveLinkValues

True if Microsoft Excel saves external link values with the workbook. Read/writeBoolean.

PasswordEncryptionProvider

Path

Permission

Returns a String specifying the name of the algorithm encryption provider that Microsoft Excel uses when encrypting passwords for the specified workbook. Read-only. Returns a String that represents the complete path to the workbook/file that this workbook object respresents. Returns a Permission object that represents the permission settings in the specified workbook.

PersonalViewListSettings

True if filter and sort settings for lists are included in the user's personal view of the shared workbook. Read/write Boolean.

PersonalViewPrintSettings

True if print settings are included in the user's personal view of the shared workbook. Readwrite Boolean.

PivotTables

Returns an object that represents a collection of all the PivotTable reports on a worksheet. Read-only.

ServerPolicy

Returns a ServerPolicy object that represents a policy specified for a workbook stored on a server running SharePoint Server 2007 or later. Read-only.

ServerViewableItems

Allows a developer to interact with the list of published objects in the workbook that are shown on the server. Read-only.

SharedWorkspace

This object or member has been deprecated, but it remains part of the object model for backward compatibility. You should not use it in new applications.

Sheets

Returns a Sheets collection that represents all the sheets in the specified workbook. Readonly Sheets object.

ShowConflictHistory

True if the Conflict History worksheet is visible in the workbook that's open as a shared list. Read/write Boolean.

ShowPivotChartActiveFields

This property controls the visibility of the PivotChart Filter Pane. Read/writeBoolean.

ShowPivotTableFieldList

True (default) if the PivotTable field list can be shown. Read/write Boolean.

Signatures

Returns the digital signatures for a workbook. Read-only.

SlicerCaches

Returns the SlicerCaches object associated with the workbook. Read-only.

SmartDocument

Returns a SmartDocument object that represents the settings for a smart document solution. Read-only.

Styles

Returns a Styles collection that represents all the styles in the specified workbook. Readonly.

Sync

This object or member has been deprecated, but it remains part of the object model for backward compatibility. You should not use it in new applications.

TableStyles

Returns a TableStyles collection object for the current workbook that refers to the styles used in the current workbook. Read-only.

TemplateRemoveExtData

True if external data references are removed when the workbook is saved as a template. Read/write Boolean.

Theme

Returns the theme applied to the current workbook. Read-only.

UpdateLinks

Returns or sets an XlUpdateLink constant indicating a workbook's setting for updating embedded OLE links. Read/write.

UpdateRemoteReferences

True if Microsoft Excel updates remote references in the workbook. Read/writeBoolean.

UserStatus

Returns a 1-based, two-dimensional array that provides information about each user who has the workbook open as a shared list. Readonly Variant.

UseWholeCellCriteria

True if the workbook uses search patterns that match the entire content of a cell. Readonly Boolean.

UseWildcards

True if the workbook enables wildcards for character string comparisons and searching. Read-only Boolean

VBASigned

True if the Visual Basic for Applications project for the specified workbook has been digitally signed. Read-only Boolean.

VBProject

Returns a VBProject object that represents the Visual Basic project in the specified workbook. Read-only.

WebOptions

Returns the WebOptions collection, which contains workbook-level attributes used by Microsoft Excel when you save a document as a Web page or open a Web page. Read-only.

Windows

Returns a Windows collection that represents all the windows in the specified workbook. Read-only Windows object.

Worksheets

Returns a Sheets collection that represents all the worksheets in the specified workbook. Read-only Sheets object.

WritePassword

Returns or sets a String for the write password of a workbook. Read/write.

WriteReserved

True if the workbook is write-reserved. Readonly Boolean.

WriteReservedBy

Returns the name of the user who currently has write permission for the workbook. Readonly String.

XmlMaps

Returns an XmlMaps collection that represents the schema maps that have been added to the specified workbook. Read-only.

XmlNamespaces

Returns an XmlNamespaces collection that represents the XML namespaces contained in the specified workbook. Read-only.

Application. Sheets When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application..

Syntax expression .Application expression A variable that represents a Sheets object.

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 an Excel Application object." Else MsgBox "This is not an Excel Application object." End If

Sheets Collection A collection of all the sheets in the specified or active workbook.

Remarks The Sheets collection can contain Chart or Worksheet objects. The Sheets collection is useful when you want to return sheets of any type. If you need to work with sheets of only one type, see the object topic for that sheet type.

Example Use the Sheets property to return the Sheets collection. The following example prints all sheets in the active workbook. Sheets.PrintOut

Use the Add method to create a new sheet and add it to the collection. The following example adds two chart sheets to the active workbook, placing them after sheet two in the workbook. Sheets.Add type:=xlChart, count:=2, after:=Sheets(2)

Use Sheets(index), where index is the sheet name or index number, to return a single Chart or Worksheet object. The following example activates the sheet named "sheet1." Sheets("sheet1").Activate

Use Sheets(array) to specify more than one sheet. The following example moves the sheets named "Sheet4" and "Sheet5" to the beginning of the workbook. Sheets(Array("Sheet4", "Sheet5")).Move before:=Sheets(1)

Sheets Object A collection of all the sheets in the specified or active workbook.

Methods Name

Description

Add

Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.

Add2

This method is only implemented for the Charts collection object and will produce a run time error if used on the Sheets and Worksheets objects.

Copy

Copies the sheet to another location in the workbook.

Delete

Deletes the object.

FillAcrossSheets

Copies a range to the same area on all other worksheets in a collection.

Move

Moves the sheet to another location in the workbook.

PrintOut

Prints the object.

PrintPreview

Shows a preview of the object as it would look when printed.

Select

Selects the object.

Properties Name

Description

Application

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When 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 application of that object). Read-only.

Count

Returns a Long value that represents the number of objects in the collection.

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.

HPageBreaks

Returns an HPageBreaks collection that represents the horizontal page breaks on the sheet. Read-only.

Item

Returns a single object from a collection.

Parent

Returns the parent object for the specified object. Readonly.

Visible

Returns or sets a Variant value that determines whether the object is visible.

VPageBreaks

Returns a VPageBreaks collection that represents the vertical page breaks on the sheet. Read-only.

Application. WorkSheets For an Application object, returns a Sheets collection that represents all the worksheets in the active workbook. For a Workbook object, returns a Sheets collection that represents all the worksheets in the specified workbook. Read-only Sheets object.

Syntax expression .Worksheets expression A variable that represents an Application object.

Remarks Using this property without an object qualifier returns all the worksheets in the active workbook. This property doesn’t return macro sheets; use the Excel4MacroSheets property or the Excel4IntlMacroSheets property to return those sheets.

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 = "current Budget"

WorkSheets Object A collection of all the Worksheet objects in the specified or active workbook. Each Worksheet object represents a worksheet.

Remarks The Worksheet object is also a member of the Sheets collection. The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).

Example Use the Worksheets property to return the Worksheets collection.The following example moves all the worksheets to the end of the workbook. Worksheets.Move After:=Sheets(Sheets.Count)

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 Worksheets(index), where index is the worksheet index number or name, to return a single Worksheet object. The following example hides worksheet one in the active workbook. Worksheets(1).Visible = False

Methods

Properties

Name

Description

Name

Description

Add

Creates a new worksheet, chart, or macro sheet. The new worksheet becomes the active sheet.

Application

Add2

This method is only implemented for the Charts collection object and will produce a run time error if used on the Sheets and Worksheets objects.

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When used with an object qualifier, this property returns an Applicationobject that represents the creator of the specified object (you can use this property with an OLE Automation object to return the application of that object). Read-only.

Copy

Copies the sheet to another location in the workbook.

Count

Returns a Long value that represents the number of objects in the collection.

Delete

Deletes the object.

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.

FillAcrossSheets

Copies a range to the same area on all other worksheets in a collection.

HPageBreaks

Returns an HPageBreaks collection that represents the horizontal page breaks on the sheet. Read-only.

Move

Moves the sheet to another location in the workbook.

Item

Returns a single object from a collection.

PrintOut

Prints the object.

Parent

Returns the parent object for the specified object. Readonly.

PrintPreview

Shows a preview of the object as it would look when printed.

Visible

Returns or sets a Variant value that determines whether the object is visible.

Select

Selects the object.

VPageBreaks

Returns a VPageBreaks collection that represents the vertical page breaks on the sheet. Read-only.

WorkSheet Object Represents a worksheet.

Remarks The Worksheet object is a member of the Worksheets collection. The Worksheets collection contains all the Worksheet objects in a workbook. The Worksheet object is also a member of the Sheets collection. The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).

Example Use Worksheets(index), where index is the worksheet index number or name, to return a single Worksheet object. The following example hides worksheet one in the active workbook. Worksheets(1).Visible = False

The worksheet index number denotes the position of the worksheet on the workbook’s tab bar. Worksheets(1) is the first (leftmost) worksheet in the workbook, and Worksheets(Worksheets.Count) is the last one. All worksheets are included in the index count, even if they’re hidden. 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 Sheet1. Dim strPassword As String strPassword = InputBox ("Enter the password for the worksheet") Worksheets("Sheet1").Protect password:=strPassword, scenarios:=True

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 Sheet1, sets the page orientation to landscape mode, and then prints the worksheet. Worksheets("Sheet1").Activate

Events Name

Description

Activate

Occurs when a workbook, worksheet, chart sheet, or embedded chart is activated.

ActiveSheet.PageSetup.Orientation = xlLandscape ActiveSheet.PrintOut BeforeDelete BeforeDoubleClick

Occurs when a worksheet is double-clicked, before the default double-click action.

BeforeRightClick

Occurs when a worksheet is right-clicked, before the default right-click action.

Calculate

Occurs after the worksheet is recalculated, for the Worksheet object.

Change

Occurs when cells on the worksheet are changed by the user or by an external link.

Deactivate

Occurs when the chart, worksheet, or workbook is deactivated.

FollowHyperlink

Occurs when you click any hyperlink on a worksheet. For application- and workbooklevel events, see the SheetFollowHyperlink event andSheetFollowHyperlink event.

LensGalleryRenderComplete

Occurs when a callout gallery’s icons (dynamic & static) have completed rendering.

PivotTableAfterValueChange

Occurs after a cell or range of cells inside a PivotTable are edited or recalculated (for cells that contain formulas).

PivotTableBeforeAllocateChanges

Occurs before changes are applied to a PivotTable.

PivotTableBeforeCommitChanges

Occurs before changes are committed against the OLAP data source for a PivotTable.

PivotTableBeforeDiscardChanges

Occurs before changes to a PivotTable are discarded.

PivotTableChangeSync

Occurs after changes to a PivotTable.

PivotTableUpdate

Occurs after a PivotTable report is updated on a worksheet.

SelectionChange

Occurs when the selection changes on a worksheet.

TableUpdate

Occurs after a Query table connected to the Data Model is updated on a worksheet.

Methods Name

Description

Activate

Makes the current sheet the active sheet.

Calculate

Calculates all open workbooks, a specific worksheet in a workbook, or a specified range of cells on a worksheet, as shown in the following table.

ChartObjects

Returns an object that represents either a single embedded chart (a ChartObject object) or a collection of all the embedded charts (a ChartObjects object) on the sheet.

CheckSpelling

Checks the spelling of an object.

CircleInvalid

Circles invalid entries on the worksheet.

ClearArrows

Clears the tracer arrows from the worksheet. Tracer arrows are added by using the auditing feature.

ClearCircles

Clears circles from invalid entries on the worksheet.

Copy

Copies the sheet to another location in the workbook.

Delete

Deletes the object.

Evaluate

Converts a Microsoft Excel name to an object or a value.

ExportAsFixedFormat

Exports to a file of the specified format.

Move

Moves the sheet to another location in the workbook.

OLEObjects

Returns an object that represents either a single OLE object (an OLEObject ) or a collection of all OLE objects (an OLEObjects collection) on the chart or sheet. Readonly.

Paste

Pastes the contents of the Clipboard onto the sheet.

PasteSpecial

Pastes the contents of the Clipboard onto the sheet, using a specified format. Use this method to paste data from other applications or to paste data in a specific format.

PivotTables

PivotTableWizard

Returns an object that represents either a single PivotTable report (a PivotTable object) or a collection of all the PivotTable reports (a PivotTables object) on a worksheet. Read-only. Creates a new PivotTable report. This method doesn’t display the PivotTable Wizard. This method isn’t available for OLE DB data sources. Use the Add method to add a PivotTable cache, and then create a PivotTable report based on the cache.

PrintOut

Prints the object.

PrintPreview

Shows a preview of the object as it would look when printed.

Protect

Protects a worksheet so that it cannot be modified.

ResetAllPageBreaks

Resets all page breaks on the specified worksheet.

SaveAs

Saves changes to the chart or worksheet in a different file.

Scenarios

Returns an object that represents either a single scenario (a Scenario object) or a collection of scenarios (a Scenarios object) on the worksheet.

Select

Selects the object.

SetBackgroundPicture

Sets the background graphic for a worksheet.

ShowAllData

Makes all rows of the currently filtered list visible. If AutoFilter is in use, this method changes the arrows to "All."

ShowDataForm

Displays the data form associated with the worksheet.

Unprotect

Removes protection from a sheet or workbook. This method has no effect if the sheet or workbook isn't protected.

XmlDataQuery

Returns a Range object that represents the cells mapped to a particular XPath. Returns Nothingif the specified XPath has not been mapped to the worksheet, or if the mapped range is empty.

XmlMapQuery

Returns a Range object that represents the cells mapped to a particular XPath. Returns Nothingif the specified XPath has not been mapped to the worksheet.

Properties Name

Description

Application

When used without an object qualifier, this property returns an Application object that represents the Microsoft Excel application. When 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 application of that object). Read-only.

active document isn't a worksheet, the Columns property fails. Comments

Returns a Comments collection that represents all the comments for the specified worksheet. Read-only.

ConsolidationFunction

Returns the function code used for the current consolidation. Can be one of the constants of XlConsolidationFunction. Read-only Long.

ConsolidationOptions

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

AutoFilter

Returns an AutoFilter object if filtering is on. Read-only.

AutoFilterMode

True if the AutoFilter drop-down arrows are currently displayed on the sheet. This property is independent of the FilterMode property. Read/write Boolean.

ConsolidationSources

Returns an array of string values that name the source sheets for the worksheet's current consolidation. Returns Empty if there's no consolidation on the sheet. Read-only Variant.

Cells

Returns a Range object that represents all the cells on the worksheet (not just the cells that are currently in use).

Creator

Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.

CircularReference

Returns a Range object that represents the range containing the first circular reference on the sheet, or returns Nothing if there's no circular reference on the sheet. The circular reference must be removed before calculation can proceed.

CustomProperties

Returns a CustomProperties object representing the identifier information associated with a worksheet.

DisplayPageBreaks

True if page breaks (both automatic and manual) on the specified worksheet are displayed. Read/write Boolean.

DisplayRightToLeft

True if the specified worksheet is displayed from right to left instead of from left to right. False if the object is displayed from left to right. Read-only Boolean.

CodeName

Columns

Returns the code name for the object. Read-only String. Returns a Range object that represents all the columns on the active worksheet. If the

EnableAutoFilter

True if AutoFilter arrows are enabled when user-interface-only protection is turned on. Read/write Boolean.

ListObjects

Returns a collection of ListObject objects in the worksheet. Readonly ListObjectscollection.

EnableCalculation

True if Microsoft Excel automatically recalculates the worksheet when necessary.False if Excel doesn't recalculate the sheet. Read/write Boolean.

MailEnvelope

Rrepresents an e-mail header for a document.

Name

Returns or sets a String value that represents the object name.

Names

Returns a Names collection that represents all the worksheet-specific names (names defined with the "WorksheetName!" prefix). Readonly Names object.

Next

Returns a Worksheet object that represents the next sheet.

Outline

Returns an Outline object that represents the outline for the specified worksheet. Read-only.

PageSetup

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

Parent

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

Previous

Returns a Worksheet object that represents the next sheet.

Returns a Hyperlinks collection that represents the hyperlinks for the worksheet.

PrintedCommentPages

Returns the number of comment pages that will be printed for the current worksheet. Read-only

Returns a Long value that represents the index number of the object within the collection of similar objects.

ProtectContents

True if the contents of the sheet are protected. This protects the individual

EnableFormatConditionsCalculation

Returms or sets if conditional formats will will occur automatically as needed. Read/write Boolean.

EnableOutlining

True if outlining symbols are enabled when user-interface-only protection is turned on. Read/write Boolean.

EnablePivotTable

True if PivotTable controls and actions are enabled when user-interface-only protection is turned on. Read/write Boolean.

EnableSelection

Returns or sets what can be selected on the sheet. Read/write XlEnableSelection.

FilterMode

True if the worksheet is in the filter mode. Read-only Boolean.

HPageBreaks

Returns an HPageBreaks collection that represents the horizontal page breaks on the sheet. Read-only.

Hyperlinks

Index

cells. To turn on content protection, use the Protect method with the Contentsargument set to True. Readonly Boolean. ProtectDrawingObjects

True if shapes are protected. To turn on shape protection, use the Protectmethod with the DrawingObjects argument set to True. Read-only Boolean.

Shapes

Returns a Shapes collection that represents all the shapes on the worksheet. Read-only.

Sort

Returns a Sort object. Read-only.

StandardHeight

Returns the standard (default) height of all the rows in the worksheet, in points. Readonly Double.

Protection

Returns a Protection object that represents the protection options of the worksheet.

StandardWidth

Returns or sets the standard (default) width of all the columns in the worksheet. Read/write Double.

ProtectionMode

True if user-interface-only protection is turned on. To turn on user interface protection, use the Protect method with the UserInterfaceOnly argument set toTrue. Read-only Boolean.

Tab

Returns a Tab object for a worksheet.

TransitionExpEval

True if Microsoft Excel uses Lotus 1-2-3 expression evaluation rules for the worksheet. Read/write Boolean.

TransitionFormEntry

True if Microsoft Excel uses Lotus 1-2-3 formula entry rules for the worksheet. Read/write Boolean.

Type

Returns an XlSheetType value that represents the worksheet type.

UsedRange

Returns a Range object that represents the used range on the specified worksheet. Read-only.

Visible

Returns or sets an XlSheetVisibility value that determines whether the object is visible.

VPageBreaks

Returns a VPageBreaks collection that represents the vertical page breaks on the sheet. Read-only.

ProtectScenarios

True if the worksheet scenarios are protected. Read-only Boolean.

QueryTables

Returns the QueryTables collection that represents all the query tables on the specified worksheet. Read-only.

Range

Returns a Range object that represents a cell or a range of cells.

Rows

Returns a Range object that represents all the rows on the specified worksheet. Readonly Range object.

ScrollArea

Returns or sets the range where scrolling is allowed, as an A1-style range reference. Cells outside the scroll area cannot be selected. Read/write String.

Propiedad Worksheet.Cells (Excel) Devuelve un objeto Range que representa todas las celdas de la hoja de cálculo (no solo las celdas que están actualmente en uso).

Sintaxis

expresión .Cells

expresión Variable que representa un objeto WorkSheet.

Propiedad Worksheet.Columns Devuelve un objeto Range que representa todas las columnas de la hoja de cálculo activa. Si el documento activo no es una hoja de cálculo, la propiedad Columns devuelve un error.

Sintaxis

expresión Variable que representa un objeto WorkSheet.

Observaciones Dado que la propiedad Item es la propiedad predeterminada del objeto Range , puede especificar el índice de fila y columna inmediatamente después de la palabra clave de las celdas . Para obtener más información, vea la propiedad Item y los ejemplos de este tema. Si se usa esta propiedad sin un calificador de objeto, se devuelve un objeto Range que representa todas las celdas de la hoja activa.

Ejemplo En este ejemplo se establece el tamaño de fuente para la celda C5 de Sheet1 en 14 puntos.

expresión .Columns

Observaciones El uso de esta propiedad sin un calificador de objeto equivale a usar ActiveSheet.Columns. Si se aplica a un objeto Range que es una selección de varias áreas, la propiedad únicamente devuelve las columnas de la primera área del rango. Por ejemplo, si el objeto Range tiene dos áreas, A1:B2 y C3:D4, Selection.Columns.Count devuelve 2, no 4. Si desea utilizar esta propiedad en un rango que puede contener una selección de varias áreas, compruebe Areas.Count para determinar si el rango contiene más de un área. En ese caso, ejecute un bucle sobre cada área del rango.

Ejemplo

Worksheets("Sheet1").Cells(5, 3).Font.Size = 14

En este ejemplo se da formato de negrita a la fuente de la columna uno (columna A) de Sheet1.

En este ejemplo se borra la fórmula de la celda uno de Sheet1.

Worksheets("Sheet1").Columns(1).Font.Bold = True

Worksheets("Sheet1").Cells(1).ClearContents

En este ejemplo se establece en Arial de 8 puntos la fuente y el tamaño de fuente de todas las celdas de Sheet1. With Worksheets("Sheet1").Cells.Font

Propiedad Worksheet.Comments (Excel) Devuelve una colección de Comments que representa todos los comentarios de la hoja de cálculo especificada. Solo lectura.

.Name = "Arial" .Size = 8 End With

Sintaxis

expresión .Comments expresión Variable que representa un objeto WorkSheet.

En el ejemplo de código siguiente se establece el nombre de la hoja de cálculo activa de igual a la fecha actual.

Ejemplo Este ejemplo elimina todos los comentarios agregados por Jean Selva a la hoja activa. For Each c in ActiveSheet.Comments If c.Author = "Jean Selva" Then c.Delete Next

VBA ' This macro sets today's date as the name for the current sheet Sub NameWorksheetByDate() Range("D5").Select Selection.Formula = "=text(now(),""mmm dd yyyy"")" Selection.Copy

Propiedad Worksheet.EnableAutoFilter True si están habilitadas las flechas de filtro automático cuando se activa la protección de solo interfaz de usuario. Boolean de lectura y escritura.

Sintaxis

expresión .EnableAutoFilter

Ejemplo Este ejemplo activa las flechas de Autofiltro en una hoja de cálculo protegida. ActiveSheet.EnableAutoFilter = True ActiveSheet.Protect contents:=True, userInterfaceOnly:=True

Propiedad Worksheet.Name (Excel) Devuelve o establece un valor de tipo String que representa el nombre del objeto. expresión .Name expresión Variable que representa un objeto WorkSheet.

Ejemplos

Application.CutCopyMode = False Selection.Columns.AutoFit ActiveSheet.Name = Range("D5").Value Range("D5").Value = ""

expresión Variable que representa un objeto WorkSheet.

Sintaxis

Selection.PasteSpecial Paste:=xlValues

End Sub

Propiedad Worksheet.Next (Excel) Devuelve un objeto Worksheet que representa la hoja siguiente.

Sintaxis

expresión .Next expresión Variable que representa un objeto WorkSheet.

Observaciones Si el objeto es un rango, esta propiedad emula a la tecla TAB, aunque la propiedad devuelve la celda siguiente sin seleccionarla. En una hoja protegida, esta propiedad devuelve la siguiente celda desbloqueada. En una hoja desprotegida, siempre devuelve la celda situada inmediatamente a la derecha de la celda especificada.

Ejemplo En este ejemplo se selecciona la siguiente celda desbloqueada de Sheet1. Si Sheet1 no está protegida, ésta será la celda situada inmediatamente a la derecha de la celda activa. Worksheets("Sheet1").Activate ActiveCell.Next.Select

En una hoja protegida, esta propiedad devuelve la celda anterior no bloqueada. En una hoja desprotegida, la propiedad siempre devuelve la celda situada inmediatamente a la izquierda de la celda especificada.

Ejemplo En este ejemplo se selecciona la celda anterior no bloqueada de Sheet1. Si Sheet1 no está protegida, será la celda situada inmediatamente a la izquierda de la celda activa. Worksheets("Sheet1").Activate ActiveCell.Previous.Select

Propiedad Worksheet.Protection Devuelve un objeto Protection que representa las opciones de protección de la hoja de cálculo.

Sintaxis

expresión .Protection expresión Variable que representa un objeto WorkSheet.

Ejemplo Este ejemplo protege la hoja de cálculo activa; a continuación, determina si se pueden insertar columnas en la hoja de cálculo y comunica al usuario este estado. Sub CheckProtection()

Propiedad Worksheet.Previous (Excel) Devuelve un objeto Worksheet que representa la hoja anterior.

Sintaxis

ActiveSheet.Protect ' Check the ability to insert columns on a protected sheet. 'Notify the user of this status. If ActiveSheet.Protection.AllowInsertingColumns = True Then

expresión .Previous

MsgBox "The insertion of columns is allowed on this _

expresión Variable que representa un objeto WorkSheet.

protected worksheet." Else

Observaciones Si el objeto es un rango, esta propiedad emula la acción de presionar las teclas MAYÚS+TAB; no obstante, a diferencia de la combinación de teclas, la propiedad devuelve la celda anterior sin seleccionarla.

MsgBox "The insertion of columns is not allowed on _ this protected worksheet." End If End Sub

Propiedad Worksheet.Range (Excel) Devuelve un objeto Range que representa una celda o un rango de celdas.

Sintaxis

expresión .Range(Cell1, Cell2) expresión Variable que representa un objeto WorkSheet.

Parámetros

Cell2

Ejemplo En este ejemplo se establece el valor de la celda A1 de Sheet1 como 3.14159. Worksheets("Sheet1").Range("A1").Value = 3.14159

Nombre Cell1

da, Selection.Range("B1") devuelve la celda D3 porque es el valor relativo al objeto Range devuelto por la propiedad Selection. Por otro lado, el código ActiveSheet.Range("B1") siempre devuelve la celda B1.

Descripción Obligatorio

Opcional

Nombre del rango. Debe ser una referencia de estilo A1 en el lenguaje de la macro. Puede incluir un operador de rango (dos puntos), de intersección (espacio) o de unión (coma). Admite signos de dólar, pero no se tendrán en cuenta. Se puede usar un nombre local definido en cualquier parte del rango. Si se usa un nombre, se supone que está en el lenguaje de la macro. Celda de las esquinas superior izquierda e inferior derecha del rango. Puede ser un objeto Range que contiene una sola celda, una columna completa o una fila completa; o bien una cadena que hace referencia a una sola celda en el lenguaje de la macro.

En este ejemplo se crea una fórmula en la celda A1 de Sheet1. Worksheets("Sheet1").Range("A1").Formula = "=10*RAND()"

En este ejemplo se ejecuta un bucle sobre las celdas A1:D10 de Sheet1.Si una de las celdas tiene un valor menor que 0.001, el código sustituye el valor por 0 (cero). For Each c in Worksheets("Sheet1").Range("A1:D10") If c.Value < .001 Then c.Value = 0 End If Next c

En este ejemplo se ejecuta un bucle en el rango denominado "TestRange" y se muestra el número de celdas vacías del rango. numBlanks = 0 For Each c In Range("TestRange") If c.Value = "" Then numBlanks = numBlanks + 1

Observaciones Si no hace referencia a ningún objeto, esta propiedad es una abreviatura de ActiveSheet.Range (devuelve un rango de la hoja activa; si la hoja activa no es una hoja de cálculo, la propiedad no funciona). Cuando se aplica a un objeto Range, los valores de la propiedad son relativos al objeto Range. Por ejemplo, si la celda C3 está selecciona-

End If Next c MsgBox "There are " & numBlanks & " empty cells in this range"

En este ejemplo se establece en cursiva el estilo de fuente de las celdas A1:C5 de Sheet1.El ejemplo usa la sintaxis 2 de la propiedad Range. Worksheets("Sheet1").Range(Cells(1, 1), Cells(5, 3))._ Font.Italic = True

Propiedad Worksheet.Rows (Excel) Devuelve un objeto Range que representa todas las filas de la hoja de cálculo especificada. Objeto Range de solo lectura.

En este ejemplo se muestra el número de filas de la selección de Sheet1.Si se ha seleccionado más de un área, el ejemplo ejecuta un bucle en cada área. Worksheets("Sheet1").Activate areaCount = Selection.Areas.Count

Sintaxis

expresión .Rows

expresión Variable que representa un objeto WorkSheet.

Observaciones El uso de esta propiedad sin un calificador de objeto equivale a usar ActiveSheet.Rows.

If areaCount 1 Then MsgBox "Cannot do this to a multi-area selection." End If

Propiedad Range.Borders Devuelve una colección Borders que representa los bordes de un estilo o de un rango de celdas.

Si se usa esta propiedad sin un calificador de objeto, se devuelve un objeto Range que representa todas las celdas de la hoja activa.

Ejemplo En este ejemplo se establece el estilo de fuente de las celdas A1:C5 de Sheet1 como cursiva. Worksheets("Sheet1").Activate Range.Item(Cells(1, 1), Cells(5, 3)).Font.Italic = True

Sintaxis

expresión .Borders expresión Variable que representa un objeto Range.

Ejemplo Borde fino de color rojo para el borde inferior de la celda B2 de Sheet1. Sub SetRangeBorder()

En este ejemplo se examina una columna de datos denominados "myRange".Si una celda tiene el mismo valor que la celda situada inmediatamente sobre él, en el ejemplo se muestra la dirección de la celda que contiene los datos duplicados. Set r = Range("myRange") For n = 1 To r.Rows.Count If r.Cells(n, 1) = r.Cells(n + 1, 1) Then

With Worksheets("Sheet1").Range("B2").Borders(xlEdgeBottom)

MsgBox "Duplicate data in " & _

.LineStyle = xlContinuous .Weight = xlThin .ColorIndex = 3 End With End Sub

r.Cells(n + 1, 1).Address End If Next n

Propiedad Range.Characters

Propiedad Range.Column

Devuelve un objeto Characters que representa un rango de caracteres de texto del objeto. Puede usar el objeto Characters a formato de caracteres dentro de una cadena de texto.

Devuelve el número de la primera columna del primer área del rango especificado. Long de sólo lectura.

Sintaxis

Sintaxis

expresión .Column

expresión .Characters(Start, Length)

expresión Variable que representa un objeto Range.

expresión Variable que representa un objeto Range.

Parámetros

Observaciones

Nombre

Necesario/Opcional

Descripción

Start

Opcional

Primer carácter que se debe devolver. Si el argumento es 1 o no se especifica, la propiedad devuelve un rango de caracteres que empieza con el primer carácter.

Length

Opcional

Número de caracteres que se deben devolver. Si no se especifica este argumento, la propiedad devuelve el resto de la cadena (todo lo que esté después del carácter Start).

Column A devuelve 1, column B devuelve 2, y así sucesivamente. Para devolver el número de la última columna del rango, use la expresión siguiente: myRange.Columns(myRange.Columns.Count).Column

Ejemplo Este ejemplo establece en 4 puntos el ancho de las columnas alternas de Sheet1. For Each col In Worksheets("Sheet1").Columns If col.Column Mod 2 = 0 Then col.ColumnWidth = 4 End If

Observaciones El objeto Characters no es una colección.

Ejemplo En este ejemplo se da formato de negrita al tercer carácter de la celda A1 de Sheet1. With Worksheets("Sheet1").Range("A1") .Value = "abcdefg" .Characters(3, 1).Font.Bold = True End With

Next col

Propiedad Range.Columns Devuelve un objeto Range que representa las columnas del rango especificado.

Sintaxis

expresión .Columns

expresión Variable que representa un objeto Range.

Observaciones El uso de esta propiedad sin un calificador de objeto equivale a usar ActiveSheet.Columns.

En este ejemplo se muestra el número de columnas de la selección de Sheet1.Si se ha seleccionado más de un área, el ejemplo ejecuta un bucle en cada área. Worksheets("Sheet1").Activate areaCount = Selection.Areas.Count If areaCount
View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF