Manual de Referencia VBA Excel
Manual de Referencia VBA Excel
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
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
Events
Name
Description
AfterCalculate
NewWorkbook
ProtectedViewWindowActivate
ProtectedViewWindowBeforeClose
ProtectedViewWindowBeforeEdit
ProtectedViewWindowDeactivate
ProtectedViewWindowOpen
ProtectedViewWindowResize
Occurs
when
any
View window is resized.
SheetActivate
SheetBeforeDelete
SheetBeforeDoubleClick
SheetBeforeRightClick
SheetCalculate
SheetChange
SheetDeactivate
SheetFollowHyperlink
SheetLensGalleryRenderComplete
SheetPivotTableAfterValueChange
SheetPivotTableBeforeAllocateChanges
SheetPivotTableBeforeCommitChanges
Protected
SheetPivotTableBeforeDiscardChanges
SheetPivotTableUpdate
WorkbookBeforeClose
SheetSelectionChange
WorkbookBeforePrint
WorkbookBeforeSave
SheetTableUpdate
WorkbookBeforeXmlExport
WindowActivate
WindowDeactivate
WorkbookBeforeXmlImport
WindowResize
WorkbookDeactivate
WorkbookModelChange
WorkbookNewChart
WorkbookNewSheet
WorkbookOpen
WorkbookPivotTableCloseConnection
report
WorkbookPivotTableOpenConnection
report
WorkbookActivate
WorkbookAddinInstall
WorkbookAddinUninstall
WorkbookAfterSave
WorkbookAfterXmlExport
WorkbookAfterXmlImport
any
open
Methods
Name
Description
ActivateMicrosoftApp
AddCustomList
Calculate
CalculateFull
CalculateFullRebuild
CentimetersToPoints
DisplayXMLSourcePane
DoubleClick
Evaluate
FindFile
GetCustomListContents
GetCustomListNum
GetOpenFilename
GetSaveAsFilename
Goto
CheckAbort
ConvertFormula
Help
InchesToPoints
InputBox
DeleteCustomList
Intersect
MacroOptions
SendKeys
Undo
Union
Volatile
Wait
OnKey
OnRepeat
OnTime
OnUndo
Quit
RecordMacro
Repeat
Run
Properties
Name
Description
ActiveCell
ActiveChart
ActiveEncryptionSession
ActivePrinter
ActiveProtectedViewWindow
ActiveSheet
ActiveWindow
ActiveWorkbook
AddIns
AddIns2
AlertBeforeOverwriting
AltStartupPath
AlwaysUseClearType
Application
ArbitraryXMLSupportAvailable
CellDragAndDrop
AskToUpdateLinks
Cells
AutoCorrect
ChartDataPointTrack
AutomationSecurity
Returns or sets
an MsoAutomationSecurity constant that
represents the security mode Microsoft Excel
uses when programmatically opening files.
Read/write.
Charts
Columns
COMAddIns
AutoRecover
CommandBars
CalculateBeforeSave
ConstrainNumeric
ControlCharacters
CopyObjectsWithCells
AutoPercentEntry
Calculation
Caption
Cursor
CustomListCount
CutCopyMode
DataEntryMode
DecimalSeparator
DefaultFilePath
DisplayDocumentActionTaskPane
DisplayDocumentInformationPanel
DisplayFormulaAutoComplete
DisplayFormulaBar
DisplayFullScreen
DisplayFunctionToolTips
DisplayInsertOptions
DefaultSaveFormat
DisplayNoteIndicator
DisplayAlerts
DisplayPasteOptions
DisplayClipboardWindow
DisplayRecentFiles
DisplayCommentIndicator
DisplayScrollBars
DisplayStatusBar
FileValidation
EditDirectlyInCell
FileValidationPivot
EnableAutoComplete
FindFormat
FixedDecimal
FixedDecimalPlaces
FormulaBarHeight
GenerateGetPivotData
GenerateTableRefs
EnableCancelKey
EnableCheckFileExtensions
EnableEvents
ErrorCheckingOptions
ExtendList
FileConverters
FileDialog
Height
FileExportConverters
Interactive
MouseAvailable
MoveAfterReturn
MoveAfterReturnDirection
MultiThreadedCalculation
Name
Names
NewWorkbook
OnWindow
Parent
Path
IsSandboxed
Iteration
Left
LibraryPath
MapPaperSize
MaxChange
MergeInstances
MaxIterations
MeasurementUnit
PathSeparator
PivotTableSelection
PreviousSelections
PrintCommunication
PromptForSummaryInfo
ProtectedViewWindows
QuickAnalysis
Range
Ready
RecentFiles
RecordRelative
ReferenceStyle
RegisteredFunctions
ReplaceFormat
RollZoom
Rows
ScreenUpdating
Selection
Sheets
SheetsInNewWorkbook
ShowChartTipNames
SmartArtLayouts
ShowChartTipValues
SmartArtQuickStyles
ShowDevTools
StandardFont
StandardFontSize
StartupPath
StatusBar
TemplatesPath
ThisCell
ThisWorkbook
ThousandsSeparator
ShowToolTips
Top
SmartArtColors
ShowMenuFloaties
ShowQuickAnalysis
ShowSelectionFloaties
ShowStartupDialog
TransitionMenuKey
Visible
TransitionNavigKeys
WarnOnFunctionNameConflict
UsableHeight
Watches
Width
UsableWidth
UsedObjects
UserControl
Windows
WindowState
UserLibraryPath
Workbooks
WorksheetFunction
UserName
Worksheets
UseSystemSeparators
Value
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 doesnt 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.
Example
This example activates the workbook Book1.xls.
Workbooks("BOOK1").Activate
T
his example saves changes to and closes all workbooks except the one thats
running the example.
For Each w In Workbooks
If w.Name <> ThisWorkbook.Name Then
w.Close savechanges:=True
End If
Next w
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
CanCheckOut
CheckOut
Close
Open
Opens a workbook.
OpenDatabase
OpenText
OpenXML
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
Count
Creator
Item
Parent
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
Application
CanCheckOut
CheckOut
Count
Close
Open
Opens a workbook.
Creator
OpenDatabase
Item
OpenText
Parent
OpenXML
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 wont
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 youll 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 doesnt change its index number. All workbooks are included in the
index count, even if theyre 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
AddinInstall
AddinUninstall
AfterSave
AfterXmlExport
AfterXmlImport
BeforeClose
BeforePrint
BeforeSave
BeforeXmlExport
Workbooks("Cogs.xls").Worksheets("Sheet1").Activate
BeforeXmlImport
Deactivate
ModelChange
NewChart
SheetBeforeRightClick
SheetCalculate
SheetChange
SheetDeactivate
SheetFollowHyperlink
SheetLensGalleryRenderComplete
NewSheet
Open
PivotTableCloseConnection
PivotTableOpenConnection
SheetPivotTableAfterValueChange
RowsetComplete
SheetPivotTableBeforeAllocateChanges
SheetPivotTableBeforeCommitChanges
SheetPivotTableBeforeDiscardChanges
SheetPivotTableChangeSync
SheetActivate
SheetBeforeDelete
SheetBeforeDoubleClick
SheetPivotTableUpdate
SheetSelectionChange
SheetTableUpdate
Sync
WindowActivate
WindowDeactivate
WindowResize
Methods
Name
Description
AcceptAllChanges
Activate
AddToFavorites
ApplyTheme
BreakLink
CanCheckIn
ChangeFileAccess
ChangeLink
CheckIn
CheckInWithVersion
GetWorkflowTemplates
HighlightChangesOptions
LinkInfo
LinkSources
LockServerFile
MergeWorkbook
NewWindow
OpenLinks
PivotCaches
Post
PrintOut
Close
DeleteNumberFormat
EnableConnections
EndReview
ExclusiveAccess
ExportAsFixedFormat
FollowHyperlink
ForwardMailer
GetWorkflowTasks
PrintPreview
Protect
ResetColors
ProtectSharing
RunAutoMacros
PurgeChangeHistoryNow
RefreshAll
Save
RejectAllChanges
SaveAs
RemoveDocumentInformation
SaveAsXMLData
RemoveUser
SaveCopyAs
Reply
SendFaxOverInternet
SendForReview
SendMail
SendMailer
ReplyAll
ReplyWithChanges
ToggleFormsDesign
Properties
Name
Description
AccuracyVersion
ActiveChart
Unprotect
UnprotectSharing
ActiveSheet
UpdateFromFile
ActiveSlicer
UpdateLink
Application
XmlImport
XmlImportXml
AutoUpdateFrequency
AutoUpdateSaveChanges
Colors
CommandBars
ConflictResolution
Connections
ConnectionsDisabled
Container
ContentTypeProperties
Charts
CreateBackup
CheckCompatibility
Creator
CodeName
CustomDocumentProperties
Returns or sets
a DocumentProperties collection that
BuiltinDocumentProperties
CalculationVersion
CaseSensitive
ChangeHistoryDuration
ChartDataPointTrack
CustomXMLParts
Date1904
DefaultPivotTableStyle
DefaultSlicerStyle
DefaultTableStyle
DefaultTimelineStyle
DisplayDrawingObjects
DisplayInkComments
DocumentInspectors
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
EnableAutoRecover
EncryptionProvider
EnvelopeVisible
Excel4IntlMacroSheets
Excel4MacroSheets
Excel8CompatibilityMode
FileFormat
Final
ForceFullCalculation
FullName
IsInplace
KeepChangeHistory
ListChangesOnNewSheet
Mailer
FullNameURLEncoded
HasPassword
Model
HasVBProject
MultiUserEditing
HighlightChangesOnScreen
Name
IconSets
Names
InactiveListBorderVisible
Parent
Password
IsAddin
PasswordEncryptionAlgorithm
PrecisionAsDisplayed
PasswordEncryptionFileProperties
ProtectStructure
ProtectWindows
PasswordEncryptionKeyLength
PublishObjects
ReadOnly
ReadOnlyRecommended
RemovePersonalInformation
Research
RevisionNumber
Saved
SaveLinkValues
PasswordEncryptionProvider
Path
Permission
PersonalViewListSettings
PersonalViewPrintSettings
PivotTables
ServerPolicy
ServerViewableItems
SharedWorkspace
Sheets
ShowConflictHistory
ShowPivotChartActiveFields
ShowPivotTableFieldList
Signatures
SlicerCaches
SmartDocument
Styles
Sync
TableStyles
TemplateRemoveExtData
Theme
UpdateLinks
UpdateRemoteReferences
UserStatus
UseWholeCellCriteria
UseWildcards
VBASigned
VBProject
WebOptions
Windows
Worksheets
WritePassword
WriteReserved
WriteReservedBy
XmlMaps
XmlNamespaces
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
Add2
Copy
Delete
FillAcrossSheets
Move
PrintOut
PrintPreview
Select
Properties
Name
Description
Application
Count
Creator
HPageBreaks
Item
Parent
Visible
VPageBreaks
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 doesnt 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)
Methods
Properties
Name
Description
Name
Description
Add
Application
Add2
Copy
Count
Delete
Creator
FillAcrossSheets
HPageBreaks
Move
Item
PrintOut
Parent
PrintPreview
Visible
Select
VPageBreaks
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
workbooks 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 theyre 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
ActiveSheet.PageSetup.Orientation = xlLandscape
ActiveSheet.PrintOut
BeforeDelete
BeforeDoubleClick
BeforeRightClick
Calculate
Change
Deactivate
FollowHyperlink
LensGalleryRenderComplete
PivotTableAfterValueChange
PivotTableBeforeAllocateChanges
PivotTableBeforeCommitChanges
PivotTableBeforeDiscardChanges
PivotTableChangeSync
PivotTableUpdate
SelectionChange
TableUpdate
Methods
Name
Description
Activate
Calculate
ChartObjects
CheckSpelling
CircleInvalid
ClearArrows
ClearCircles
Copy
Delete
Evaluate
ExportAsFixedFormat
Move
OLEObjects
Paste
PasteSpecial
PivotTables
PivotTableWizard
PrintOut
PrintPreview
Protect
ResetAllPageBreaks
SaveAs
Scenarios
Select
SetBackgroundPicture
ShowAllData
ShowDataForm
Unprotect
XmlDataQuery
XmlMapQuery
Properties
Name
Description
Application
ConsolidationFunction
ConsolidationOptions
AutoFilter
AutoFilterMode
ConsolidationSources
Cells
Creator
CircularReference
CustomProperties
DisplayPageBreaks
DisplayRightToLeft
CodeName
Columns
EnableAutoFilter
ListObjects
EnableCalculation
MailEnvelope
Name
Names
Next
Outline
PageSetup
Parent
Previous
PrintedCommentPages
ProtectContents
EnableFormatConditionsCalculation
EnableOutlining
EnablePivotTable
EnableSelection
FilterMode
HPageBreaks
Hyperlinks
Index
Shapes
Sort
StandardHeight
Protection
StandardWidth
ProtectionMode
Tab
TransitionExpEval
TransitionFormEntry
Type
UsedRange
Visible
VPageBreaks
ProtectScenarios
QueryTables
Range
Rows
ScrollArea
Sintaxis
expresin .Cells
Propiedad Worksheet.Columns
Devuelve un objeto Range que representa todas las columnas de la hoja de
clculo activa. Si el documento activo no es una hoja de clculo, la
propiedad Columns devuelve un error.
Sintaxis
Observaciones
Dado que la propiedad Item es la propiedad predeterminada del objeto Range ,
puede especificar el ndice de fila y columna inmediatamente despus de la
palabra clave de las celdas . Para obtener ms informacin, 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 tamao de fuente para la celda C5 de Sheet1
en 14 puntos.
expresin .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 seleccin 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 seleccin de varias reas,
compruebe Areas.Count para determinar si el rango contiene ms de un
rea. En ese caso, ejecute un bucle sobre cada rea del rango.
Ejemplo
Worksheets("Sheet1").Cells(5, 3).Font.Size = 14
Worksheets("Sheet1").Columns(1).Font.Bold = True
Worksheets("Sheet1").Cells(1).ClearContents
.Name = "Arial"
.Size = 8
End With
Sintaxis
expresin .Comments
expresin Variable que representa un objeto WorkSheet.
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 estn habilitadas las flechas de filtro automtico cuando se activa la
proteccin de solo interfaz de usuario. Boolean de lectura y escritura.
Sintaxis
expresin .EnableAutoFilter
Ejemplo
Este ejemplo activa las flechas de Autofiltro en una hoja de clculo protegida.
ActiveSheet.EnableAutoFilter = True
ActiveSheet.Protect contents:=True, userInterfaceOnly:=True
Ejemplos
Application.CutCopyMode = False
Selection.Columns.AutoFit
ActiveSheet.Name = Range("D5").Value
Range("D5").Value = ""
Sintaxis
Selection.PasteSpecial Paste:=xlValues
End Sub
Sintaxis
expresin .Next
expresin 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
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 proteccin de la
hoja de clculo.
Sintaxis
expresin .Protection
expresin Variable que representa un objeto WorkSheet.
Ejemplo
Este ejemplo protege la hoja de clculo activa; a continuacin, determina si se
pueden insertar columnas en la hoja de clculo y comunica al usuario este
estado.
Sub CheckProtection()
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
expresin .Previous
protected worksheet."
Else
Observaciones
Si el objeto es un rango, esta propiedad emula la accin de presionar las teclas
MAYS+TAB; no obstante, a diferencia de la combinacin de teclas, la propiedad
devuelve la celda anterior sin seleccionarla.
Sintaxis
Parmetros
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
Descripcin
Obligatorio
Opcional
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 cdigo 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
Observaciones
Si no hace referencia a ningn 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 clculo, 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"
Sintaxis
expresin .Rows
Observaciones
El uso de esta propiedad sin un calificador de objeto equivale a
usar ActiveSheet.Rows.
Ejemplo
En este ejemplo se elimina la fila tres de Sheet1.
Worksheets("Sheet1").Rows(3).Delete
i = i + 1
Next a
End If
Application. Range
Returns a Range object that represents a cell or
a range of cells.
Syntax
expression .Range(Cell1, Cell2)
expression .[Cell1, Cell2]
expression A variable that represents an Application object.
Parameters
Name
Required/Optional
Cell1
Required
Cell2
Optional
Remarks
When used without an object qualifier, this property is a shortcut
for ActiveSheet.Range (it returns a range from the active sheet; if the active
sheet isnt a worksheet, the property fails).
When applied to a Range object, the property is relative to the Range object.
For example, if the selection is cell C3, then Selection.Range("B1") returns
cell D3 because its relative to the Range object returned by
the
Selection
property.
On
the
other
hand,
the
code ActiveSheet.Range("B1") always returns cell B1.
Example
This example sets the value of cell A1 on Sheet1 to 3.14159.
Worksheets("Sheet1").Range("A1").Value = 3.14159
This example loops on cells A1:D10 on Sheet1. If one of the cells has a value
less than 0.001, the code replaces that value with 0 (zero).
For Each c in Worksheets("Sheet1").Range("A1:D10")
If c.Value < .001 Then
c.Value = 0
End If
Next c
This example loops on the range named "TestRange" and displays the number
of empty cells in the range.
numBlanks = 0
For Each c In Range("TestRange")
If c.Value = "" Then
numBlanks = numBlanks + 1
End If
Next c
MsgBox "There are " & numBlanks & " empty cells in this range"
This example sets the font style in cells A1:C5 on Sheet1 to italic. The example
uses Syntax 2 of the Range property.
Worksheets("Sheet1").Range(Cells(1, 1), Cells(5, 3)). _
Font.Italic = True
Ranges Object
A collection of Range objects.
Properties
Name
Description
Application
Count
Creator
Item
Parent
Range Object
Represents a cell, a row, a column, a selection of
cells containing one or more contiguous blocks
of cells, or a 3-D range.
Remarks
The following properties and methods for returning a Range object are
described in the examples section:
Range property
Cells property
Range and Cells
Offset property
Union method
Example
Use Range(arg), where arg names the range, to return a Range object that
represents a single cell or a range of cells. The following example places the
value of cell A1 in cell A5.
Worksheets("Sheet1").Range("A5").Value = _
Worksheets("Sheet1").Range("A1").Value
The following example fills the range A1:H8 with random numbers by setting
the formula for each cell in the range. When its used without an object
qualifier (an object to the left of the period), the Range property returns a
range on the active sheet. If the active sheet isnt a worksheet, the method fails.
Use the Activate method to activate a worksheet before you use
the Range property without an explicit object qualifier.
Worksheets("Sheet1").Activate
Range("A1:H8").Formula = "=Rand()"
sheet
The following example clears the contents of the range named Criteria.
If you use a text argument for the range address, you must specify the
address in A1-style notation (you cannot use R1C1-style notation).
Worksheets(1).Range("Criteria").ClearContents
Use Cells(row, column) where row is the row index and column is the column
index, to return a single cell. The following example sets the value of cell A1 to
24.
Use Range(cell1, cell2), where cell1 and cell2 are Range objects that specify the
start and end cells, to return a Range object. The following example sets the
border line style for cells A1:J10.
Worksheets(1).Cells(1, 1).Value = 24
Although you can also use Range("A1") to return cell A1, there may be times
when the Cells property is more convenient because you can use a variable for
the row or column. The following example creates column and row headings
on Sheet1. Be aware that after the worksheet has been activated,
the Cells property can be used without an explicit sheet declaration (it returns
a cell on the active sheet).
Use Offset(row, column), where row and column are the row and column
offsets, to return a range at a specified offset to another range. The following
example selects the cell three rows down from and one column to the right of
the cell in the upper-left corner of the current selection. You cannot select a
cell that is not on the active sheet, so you must first activate the worksheet.
VA
Worksheets("Sheet1").Activate
'Can't select unless the sheet is active
Selection.Offset(3, 1).Range("A1").Select
If you work with selections that contain more than one area, the Areas
property is useful. It divides a multiple-area selection into individual Range
objects and then returns the objects as a collection. You can use the Count
property on the returned collection to verify a selection that contains more than
one area, as shown in the following example.
Sub NoMultiAreaSelection()
NumberOfSelectedAreas = Selection.Areas.Count
If NumberOfSelectedAreas > 1 Then
MsgBox "You cannot carry out this command " & _
"on multi-area selections"
End If
End Sub
Methods
Name
Description
Activate
AddComment
AdvancedFilter
BorderAround
Calculate
CalculateRowMajorOrder
CheckSpelling
Clear
AllocateChanges
ClearComments
ApplyNames
ClearContents
ApplyOutlineStyles
ClearFormats
AutoComplete
ClearHyperlinks
ClearNotes
AutoFill
ClearOutline
ColumnDifferences
AutoFilter
AutoFit
Consolidate
Copy
AutoOutline
CopyFromRecordset
CopyPicture
CreateNames
Cut
DataSeries
Delete
DialogBox
Dirty
DiscardChanges
EditionOptions
ExportAsFixedFormat
FillDown
FillRight
FillUp
Find
FindNext
FindPrevious
FlashFill
FunctionWizard
Group
Insert
PrintOut
PrintPreview
RemoveDuplicates
RemoveSubtotal
Replace
RowDifferences
Run
Select
SetPhonetic
Show
ShowDependents
ShowErrors
ShowPrecedents
InsertIndent
Justify
ListNames
Merge
NavigateArrow
NoteText
Parse
PasteSpecial
Sort
SortSpecial
Speak
SpecialCells
SubscribeTo
Subtotal
Table
TextToColumns
Ungroup
UnMerge
Properties
Name
Description
AddIndent
Address
AddressLocal
AllowEdit
Application
Areas
Borders
Cells
Characters
Column
Returns the number of the first column in the first area in the
specified range. Read-only Long.
DisplayFormat
Columns
End
ColumnWidth
EntireColumn
EntireRow
Returns a Range object that represents the entire row (or rows)
that contains the specified range. Read-only.
Errors
Font
FormatConditi
ons
Formula
Comment
Count
CountLarge
CurrentArray
CurrentRegion
Dependents
FormulaArray
DirectDepende
nts
FormulaHidden
FormulaLocal
FormulaR1C1
DirectPreceden
ts
FormulaR1C1L
ocal
ListHeaderRows
HasArray
ListObject
Returns a ListObject object for the Range object. Readonly ListObject object.
HasFormula
LocationInTable
Height
Locked
MergeArea
MergeCells
Name
Next
Hidden
HorizontalAlign
ment
Hyperlinks
ID
IndentLevel
NumberFormat
Interior
NumberFormat
Local
Item
Offset
Left
Orientation
OutlineLevel
ReadingOrder
Returns or sets the reading order for the specified object. Can
be one of the following constants:xlRTL (right-toleft), xlLTR (left-to-right), or xlContext. Read/write Long.
PageBreak
Resize
Parent
Row
Returns the number of the first row of the first area in the
range. Read-only Long.
Phonetic
RowHeight
Rows
ServerActions
ShowDetail
True if the outline is expanded for the specified range (so that
the detail of the column or row is visible). The specified range
must be a single summary column or row in an outline.
Read/writeVariant. For the PivotItem object (or
the Range object if the range is in a PivotTable report), this
property is set to True if the item is showing detail.
ShrinkToFit
SparklineGroups
Style
Summary
PivotCell
PivotField
PivotItem
PivotTable
Precedents
PrefixCharacter
Previous
QueryTable
Range
Text
Returns or sets the text for the specified object. Readonly String.
Top
UseStandardHeight
True if the row height of the Range object equals the standard
height of the sheet. Returns Nullif the range contains more
than one row and the rows arent all the same height.
Read/writeVariant.
UseStandardWidth
Validation
Value
Value2
VerticalAlignm
ent
Width
Worksheet
WrapText
Mtodo
Activate
Cells
Application.Goto
Offset
Range
Resize
Select
Sheets
Workbooks
End
CurrentRegion
Propiedad
ActiveSheet
ActiveWorkbook
Columns.Count
Rows.Count
Selection
Argumentos
ninguno
rowIndex, columnIndex
reference, scroll
rowOffset, columnOffset
cell1
cell1, cell2
rowSize, columnSize
ninguno
index (o sheetName)
index (o bookName)
direction
ninguno
Uso
especificar la hoja activa
especificar el libro activo
nmero de columnas en la seleccin
nmero de filas en la seleccin
referirse al rango seleccionado
Para seleccionar un rango de celdas que sea del mismo tamao que el
rango con nombre "Test" pero que estn desplazadas cuatro filas ms abajo
y tres columnas a la derecha:
a. ActiveSheet.Range("Test").Offset(4, 3).Select
Si el rango con nombre est en otra hoja (que no sea la activa), active
primero esa hoja y, a continuacin, seleccione el rango:
b. Sheets("Sheet3").Activate
ActiveSheet.Range("Test").Offset(4, 3).Select
a. Application.Intersect(Range("Test"), Range("Sample")).Select
c. ActiveSheet.Range("a1:" & _
ActiveSheet.Range("a1").End(xlDown).End(xlToRight).Address).Select
En algunos casos, es posible que desee seleccionar las celdas entre A1 y C6.
En este ejemplo, el mtodo CurrentRegion no funcionar porque hay una
lnea en blanco en la fila 5. Los ejemplos siguientes seleccionarn todas las
celdas:
a. lastCol = ActiveSheet.Range("a1").End(xlToRight).Column
lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row
ActiveSheet.Range("a1", ActiveSheet.Cells(lastRow, lastCol)).Select
b. lastCol = ActiveSheet.Range("a1").End(xlToRight).Column
lastRow = ActiveSheet.Cells(65536, lastCol).End(xlUp).Row
ActiveSheet.Range("a1:" & _
ActiveSheet.Cells(lastRow, lastCol).Address).Select
Propiedad Range.End
Sintaxis
expresin .End(Direction)
expresin Variable que representa un objeto Range.
Direction
Nombre
Descripcin
xlDown
Hacia abajo.
xlToLeft
Hacia la izquierda.
xlToRight
Hacia la derecha.
xlUp
Hacia arriba.
StartRange = "A1"
EndRange = "C1"
Set a = Range(StartRange, Range(StartRange).End(xlDown))
Set b = Range(EndRange, Range(EndRange).End(xlDown))
Union(a,b).Select
Cuando este cdigo se utilice con la tabla de ejemplo, se seleccionarn las
celdas A1:A3 y C1:C6.
Ejemplo
Este ejemplo selecciona la celda del principio de la columna B en la regin
que contiene la celda B4.
Range("B4").End(xlUp).Select
Este ejemplo selecciona la celda del final de la fila 4 en la regin que
contiene la celda B4.
Range("B4").End(xlToRight).Select
Este ejemplo ampla la seleccin desde la celda B4 hasta la ltima celda de
la fila cuatro que contenga datos.
Worksheets("Sheet1").Activate
Range("B4", Range("B4").End(xlToRight)).Select
Propiedad Range.Areas
Propiedad Range.Cells
Devuelve una coleccin de Areas que representa todos los intervalos de una
seleccin de varias reas.
Devuelve un objeto Range que representa las celdas del rango especificado.
Sintaxis
Sintaxis
expresin .Cells
expresin .Areas
expresin Variable que representa un objeto Range.
Observaciones
Ejemplo
Este ejemplo muestra un mensaje si el usuario intenta ejecutar un comando
cuando estn seleccionadas varias reas. El ejemplo debe ejecutarse desde una
hoja de clculo.
Propiedad Range.Borders
Devuelve una coleccin Borders que representa los bordes de un estilo o de un
rango de celdas.
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
expresin .Borders
expresin Variable que representa un objeto Range.
Ejemplo
Borde fino de color rojo para el borde inferior de la celda B2 de Sheet1.
Sub SetRangeBorder()
With Worksheets("Sheet1").Range("B2").Borders(xlEdgeBottom)
.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
Sintaxis
Sintaxis
expresin .Column
Parmetros
Observaciones
Nombre
Necesario/Opcional
Descripcin
Start
Opcional
Length
Opcional
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 coleccin.
Ejemplo
En este ejemplo se da formato de negrita al tercer carcter 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
expresin .Columns
Observaciones
El uso de esta propiedad sin un calificador de objeto equivale a
usar ActiveSheet.Columns.
Ejemplo
En este ejemplo se establece como 0 (cero) el valor de todas las celdas de la
columna uno del rango denominado "myRange".
Range("myRange").Columns(1).Value = 0
Propiedad Range.ColumnWidth
Devuelve o establece el ancho de las columnas del rango especificado. Variant de lectura y escritura.
Sintaxis
expresin .ColumnWidth
expresin Variable que representa un objeto Range.
Observaciones
Una unidad de ancho de columna equivale al ancho de un carcter con el estilo
Normal. En las fuentes proporcionales se utiliza el ancho del carcter 0 (cero).
Utilice la propiedad Width para devolver el ancho de una columna en puntos. Si
todas las columnas en el rango tienen el mismo ancho, lo devolver la
propiedad ColumnWidth. Si las columnas del rango tienen anchos diferentes,
la propiedad devolver Null.
Ejemplo
Ejemplos
With Worksheets("Sheet1").Columns("A")
.ColumnWidth = .ColumnWidth * 2
End With
Sub DisplayColumnCount()
Dim iAreaCount As Integer
Dim i As Integer
Propiedad Range.Comment
Devuelve un objeto Comment que representa el comentario asociado a la celda
de la esquina superior izquierda del rango.
Worksheets("Sheet1").Activate
iAreaCount = Selection.Areas.Count
If iAreaCount <= 1 Then
Sintaxis
expresin .Comment
expresin Variable que representa un objeto Range.
Propiedad Range.Count
Sintaxis
Selection.Areas(i).Columns.Count _
& " columns."
expresin .Count
expresin Variable que representa un objeto Range.
Notas
La propiedad Count es funcionalmente la misma que la propiedad CountLarge ,
excepto en que la propiedad Count generar un error de desbordamiento si el
rango especificado no tiene ms de 2,147,483,647 celdas (uno menos de 2048
columnas). Sin embargo, la propiedad CountLarge , puede controlar rangos
hasta el tamao mximo para una hoja de clculo, que es 17,179,869,184 celdas.
Next i
End If
End Sub
Propiedad Range.CurrentArray
Si la celda especificada es parte de una matriz, devuelve un objeto Range que
representa la matriz completa. Solo lectura.
En este ejemplo se supone que Sheet1 contiene una tabla con una fila de
encabezado.El ejemplo selecciona la tabla sin seleccionar la fila de
encabezado.Para poder ejecutar el ejemplo, la celda activa debe estar en la tabla.
Set tbl = ActiveCell.CurrentRegion
Sintaxis
expresin .CurrentArray
expresin Variable que representa un objeto Range.
Ejemplo
En este ejemplo se supone que la celda activa es la A1 de Sheet1 y que forma
parte de una matriz que incluye las celdas A1:A10. El ejemplo selecciona las
celdas A1:A10 de Sheet1.
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, _
tbl.Columns.Count).Select
Propiedad Range.EntireColumn
Devuelve una opcin de objeto de Range que representa la columna completa
(o columnas) que contiene el rango especificado
ActiveCell.CurrentArray.Select
Sintaxis
Propiedad Range.CurrentRegion
Devuelve un objeto Range que representa la regin actual. La regin actual es
un rango delimitado por cualquier combinacin de filas y columnas en
blanco. Solo lectura.
Sintaxis
expresin .CurrentRegion
expresin Variable que representa un objeto Range.
Observaciones
Esta propiedad es til para muchas operaciones que amplan automticamente
la seleccin para incluir toda la regin actual, por ejemplo, el
mtodo AutoFormat . Esta propiedad no se puede utilizar en hojas de clculo
protegidas.
Ejemplo
Este ejemplo selecciona la regin actual de Sheet1.
Worksheets("Sheet1").Activate
ActiveCell.CurrentRegion.Select
expresin .EntireColumn
Ejemplo
Este ejemplo establece el valor de la primera celda de la columna que contiene
la celda activa. El ejemplo debe ejecutarse desde una hoja de clculo.
ActiveCell.EntireColumn.Cells(1, 1).Value = 5
Propiedad Range.EntireRow
Devuelve una opcin de objeto de Range que representa el toda la fila (o filas)
que contiene el rango especificado.
Sintaxis
expresin .EntireRow
expresin Variable que representa un objeto Range.
Ejemplo
Este ejemplo establece el valor de la primera celda de la fila que contiene la
celda activa.
ActiveCell.EntireRow.Cells(1, 1).Value = 5
Propiedad Range.FormulaArray
Propiedad Range.FormulaHidden
Sintaxis
Sintaxis
expresin .FormulaHidden
expresin Variable que representa un objeto Range.
expresin .FormulaArray
expresin Variable que representa un objeto Range.
Observaciones
Si usa esta propiedad para escribir una frmula de matriz, la frmula deber
estar en el estilo F1C1, no en el estilo de referencia A1 (vea el segundo ejemplo).
La propiedad FormulaArray tambin tiene un lmite de 255 caracteres.
Ejemplo
Este ejemplo escribe el nmero 3 como una constante matricial en las celdas
A1:C5 de Sheet1.
Worksheets("Sheet1").Range("A1:C5").FormulaArray = "=3"
Observaciones
Esta propiedad devuelve True si la frmula va a estar oculta cuando el libro est
protegido, Null si el rango especificado contiene algunas celdas
con FormulaHidden igual a True y algunas celdas conFormulaHidden igual
a False.
Es importante no confundir esta propiedad con la propiedad Hidden . La frmula
no se ocultar si el libro est protegido y la hoja de clculo no es, pero slo si la
hoja de clculo est protegida.
Ejemplo
En este ejemplo se ocultan las frmulas de las celdas A1 y B1 de Sheet1 cuando
la hoja de clculo est protegida.
Sub HideFormulas()
Worksheets("Sheet1").Range("A1:B1").FormulaHidden = True
End Sub
Propiedad Range.FormulaR1C1
Propiedad Range.FormulaR1C1Local
Sintaxis
Sintaxis
expresin .FormulaR1C1
expresin Variable que representa un objeto Range.
expresin .FormulaR1C1Local
expresin Variable que representa un objeto Range.
Observaciones
Observaciones
Si se define el valor o la frmula de una celda como una fecha, Microsoft Excel
comprueba si dicha celda ya tiene uno de los formatos numricos de fecha u
hora. De lo contrario, cambia el formato numrico al formato numrico de fecha
corto predeterminado.
Si se define el valor o la frmula de una celda como una fecha, Microsoft Excel
comprueba si dicha celda ya tiene uno de los formatos numricos de fecha u
hora. De lo contrario, cambia el formato numrico al formato numrico de fecha
corto predeterminado.
Ejemplo
En este ejemplo se establece una frmula para la celda B1 de Sheet1.
Worksheets("Sheet1").Range("B1").FormulaR1C1 = "=SQRT(R1C1)"
Ejemplo
Supongamos que escribe la formula =SUM(A1:A10) en la celda A11 de la hoja
de clculo uno, con la versin en ingls de EE.UU. de Microsoft Excel. Si abre el
libro en un equipo en el que se usa la versin en alemn y ejecuta el ejemplo
siguiente, ste mostrar la frmula =SUMME(Z1S1:Z10S1) en un cuadro de
mensaje.
MsgBox Worksheets(1).Range("A11").FormulaR1C1Local
Propiedad Range.HasFormula
Propiedad Range.Hidden
True si todas las celdas del rango contienen frmulas; False si ninguna de las
celdas del rango contiene una frmula; null en los dems casos. Variant de slo
lectura.
Devuelve o establece un valor de tipo Variant que indica si las filas o columnas
estn ocultas.
Sintaxis
Sintaxis
expresin .HasFormula
expresin .Hidden
expresin Variable que representa un objeto Range.
Observaciones
Ejemplo
Este ejemplo solicita al usuario que seleccione un rango de Sheet1. Si todas las
celdas del rango seleccionado contienen una frmula, el ejemplo mostrar un
mensaje.
Worksheets("Sheet1").Activate
Set rr = Application.InputBox( _
prompt:="Select a range on this worksheet", _
Type:=8)
Establezca esta propiedad en True para ocultar una fila o columna. El rango
especificado debe abarcar la totalidad de una columna o una fila.
Es importante no confundir esta propiedad con la propiedad FormulaHidden .
Ejemplo
En este ejemplo se oculta la columna C de Sheet1.
Worksheets("Sheet1").Columns("C").Hidden = True
Propiedad Range.HorizontalAlignment
Devuelve o establece un valor de tipo Variant que representa la alineacin
horizontal del objeto especificado.
Propiedad Range.Height
Devuelve o establece un valor de tipo Variant que representa el alto, en puntos,
del rango.
Sintaxis
expresin .Height
expresin Variable que representa un objeto Range.
Sintaxis
expresin .HorizontalAlignment
expresin Variable que representa un objeto Range.
Observaciones
El valor de esta propiedad se puede establecer en una de las siguientes
constantes:
xlCenter
xlJustify
xlDistributed
xlLeft
xlRight
Propiedad Range.Item
Observaciones
Sintaxis
Parmetros
Nombre
Necesario/Opcional
Descripcin
RowIndex
Obligatorio
Nmero de ndice de la
celda a la que se desea
obtener acceso, por orden
de izquierda a derecha y
despus hacia abajo.
Range.Item(1)
devuelve la celda superior
izquierda del rango;
Range.Item(2)
devuelve
la
celda
inmediatamente
a
la
derecha de la celda
superior izquierda.
ColumnIndex
Opcional
Ejemplo
En este ejemplo se rellena el rango A1:A10 de Sheet1 en funcin del contenido
de la celda A1.
Worksheets("Sheet1").Range.Item("A1:A10").FillDown
Propiedad Range.Left
Devuelve un valor de tipo Variant que representa la distancia, en puntos, desde
el borde izquierdo de la columna A hasta el borde izquierdo del rango.
Sintaxis
expresin .Left
expresin Variable que representa un objeto Range.
Observaciones
Si el rango no es continuo, se usa la primera rea. Si el rango tiene ms de una
columna de ancho, se usa la columna del extremo izquierdo del rango.
Propiedad Range.ListHeaderRows
Propiedad Range.LocationInTable
Devuelve una constante que describe la parte del informe PivotTable que
contiene la esquina superior izquierda del rango especificado. Puede ser una de
las siguientes XlLocationInTable. constantes. Read-only largo.
Sintaxis
expresin .ListHeaderRows
expresin Variable que representa un objeto Range.
Sintaxis
expresin .LocationInTable
expresin Variable que representa un objeto Range.
Observaciones
Antes de usar esta propiedad, utilice la propiedad CurrentRegion para localizar
los lmites del rango.
Observaciones
Ejemplo
xlRowHeader
xlColumnHeader
iHdrRows = rTbl.ListHeaderRows
If iHdrRows > 0 Then
' resize the range minus n rows
Set rTbl = rTbl.Resize(rTbl.Rows.Count - iHdrRows)
' and then move the resized range down to
' get to the first non-header row
Set rTbl = rTbl.Offset(iHdrRows)
End If
xlPageHeader
xlDataHeader
xlRowItem
xlColumnItem
xlPageItem
xlDataItem
xlTableBody
Ejemplo
Worksheets("Sheet1").Activate
Sintaxis
Case Is = xlRowHeader
MsgBox "Active cell is part of a row header"
Case Is = xlColumnHeader
MsgBox "Active cell is part of a column header"
Case Is = xlPageHeader
MsgBox "Active cell is part of a page header"
expresin .Locked
Observaciones
Esta propiedad devuelve True si el objeto est bloqueado, False si el objeto se
puede modificar cuando la hoja est protegida o Null si el rango especificado
contiene celdas bloqueadas y desbloqueadas.
Case Is = xlDataHeader
MsgBox "Active cell is part of a data header"
Case Is = xlRowItem
MsgBox "Active cell is part of a row item"
Case Is = xlColumnItem
MsgBox "Active cell is part of a column item"
Ejemplo
En este ejemplo se desbloquean las celdas A1:G37 de Sheet1 para que puedan
modificarse si la hoja est protegida.
Worksheets("Sheet1").Range("A1:G37").Locked = False
Worksheets("Sheet1").Protect
Case Is = xlPageItem
MsgBox "Active cell is part of a page item"
Case Is = xlDataItem
MsgBox "Active cell is part of a data item"
Case Is = xlTableBody
MsgBox "Active cell is part of the table body"
End Select
Propiedad Range.Name
Devuelve o establece un valor de tipo Variant que representa el nombre del
objeto.
Sintaxis
expresin .Name
Observaciones
El nombre de un objeto Range es un objeto Name.
Ejemplo
Propiedad Range.Offset
Sub MakeName()
ActiveWorkbook.Names.Add Name:="PTable", _
RefersTo:="Sheet2!$A$1:$F$50"
End Sub
Sintaxis
Parmetros
Nombre
Necesario/Opcional
Descripcin
RowOffset
Opcional
ColumnOffset
Opcional
Nmero de columnas
(positivo, negativo o cero)
que se va a desplazar el
rango. Los valores positivos
desplazan hacia la derecha y
los negativos, hacia la
izquierda. El valor
predeterminado es 0.
Sheets("Sheet2").Activate
Range("A1").CurrentRegion.Select
ActiveWorkbook.Names.Add Name:="PTable", _
RefersTo:=Selection
End Sub
Sintaxis
expresin .Next
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 activa la celda situada tres columnas a la derecha y tres
columnas ms abajo que la celda actual de Sheet1.
Worksheets("Sheet1").Activate
ActiveCell.Offset(rowOffset:=3, columnOffset:=3).Activate
En este ejemplo se supone que Sheet1 contiene una tabla con una fila de
encabezado. El ejemplo selecciona la tabla sin seleccionar la fila de encabezado.
Debe haber una celda activada en algn lugar de la tabla antes de ejecutar el
ejemplo.
Este ejemplo elimina los dos saltos de pgina establecidos en los ejemplos
anteriores.
Worksheets("Sheet1").Rows(25).PageBreak = xlPageBreakNone
Worksheets("Sheet1").Columns("J").PageBreak = xlNone
Propiedad Range.PageBreak
Sintaxis
Ejemplo
Sintaxis
expresin .PageBreak
expresin Variable que representa un objeto Range.
Observaciones
Esta propiedad puede devolver la ubicacin de un salto de pgina manual o
automtico, pero slo puede asignar la ubicacin de los saltos de pgina
manuales (slo puede establecerse como xlPageBreakManual o
como xlPageBreakNone). Para eliminar todos los saltos de pgina manuales de
una hoja de clculo, defina Cells.PageBreak en xlPageBreakNone.
Ejemplo
Este ejemplo establece un salto de pgina manual encima de la fila 25 de Sheet1.
Worksheets("Sheet1").Rows(25).PageBreak = xlPageBreakManual
expresin .Parent
expresin Variable que representa un objeto Range.
Sintaxis
expresin .PivotCell
expresin Variable que representa un objeto Range.
Ejemplo
Propiedad Range.PivotItem
Sintaxis
Sub CheckPivotCell()
expresin .PivotItem
expresin Variable que representa un objeto Range.
Application.Range("A3").PivotCell.Parent
Ejemplo
End Sub
Propiedad Range.PivotField
Devuelve un objeto PivotField que representa el campo de tabla dinmica que
contiene la esquina superior izquierda del rango especificado.
Sintaxis
expresin .PivotField
expresin Variable que representa un objeto Range.
Ejemplo
En este ejemplo se muestra el nombre del campo de tabla dinmica que
contiene la celda activa.
Sintaxis
expresin .PivotTable
expresin Variable que representa un objeto Range.
Worksheets("Sheet1").Activate
MsgBox "The active cell is in the field " & _
ActiveCell.PivotField.Name
Ejemplo
En este ejemplo se establece la pgina actual del informe de tabla dinmica de
Sheet1 como la pgina denominada "Canada".
Set pvtTable = Worksheets("Sheet1").Range("A3").PivotTable
pvtTable.PivotFields("Country").CurrentPage = "Canada"
Propiedad Range.Range
Sintaxis
Sintaxis
expresin .Previous
expresin Variable que representa un objeto Range.
Parmetros
Observaciones
Si el objeto es un rango, esta propiedad emula la accin de presionar las teclas
MAYS+TAB; no obstante, a diferencia de la combinacin de teclas, la propiedad
devuelve la celda anterior sin seleccionarla.
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.
Nombre
Descripcin
Cell1
Obligatorio
Cell2
Opcional
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
Observaciones
Si no hace referencia a ningn 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 clculo, 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 seleccionada, Selection.Range("B1") devuelve la celda D3 porque es el valor relativo
al objeto Range devuelto por la propiedad Selection. Por otro lado, el
cdigo ActiveSheet.Range("B1") siempre devuelve la celda B1.
Ejemplo
En este ejemplo se establece el valor de la celda A1 de Sheet1 como 3.14159.
Sintaxis
Worksheets("Sheet1").Range("A1").Value = 3.14159
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 cdigo sustituye el valor por 0.
Parmetros
Nombre
Descripcin
RowSize
Opcional
ColumnSize
Opcional
Ejemplo
Este ejemplo cambia el tamao de la seleccin de Sheet1 para ampliarla una fila
y una columna.
Worksheets("Sheet1").Activate
numBlanks = numBlanks + 1
numRows = Selection.Rows.Count
End If
numColumns = Selection.Columns.Count
Next c
MsgBox "There are " & numBlanks & " empty cells in this range"
En este ejemplo se supone que Sheet1 contiene una tabla con una fila de
encabezado.El ejemplo selecciona la tabla sin seleccionar la fila de
encabezado.Para poder ejecutar el ejemplo, la celda activa debe estar en la
tabla.
Sintaxis
tbl.Offset(1, 0).Resize(tbl.Rows.Count - 1, _
Devuelve un objeto Range que representa las filas del rango especificado. Objeto Range de solo lectura.
expresin .Rows
expresin Variable que representa un objeto Range.
tbl.Columns.Count).Select
Observaciones
Propiedad Range.Row
Devuelve el nmero de la primera fila de la primera rea del rango. Long de
solo lectura.
Sintaxis
expresin .Row
expresin Variable que representa un objeto Range.
Ejemplo
Este ejemplo establece en 4 puntos el alto de las filas alternativas de Sheet1.
Ejemplo
En este ejemplo se elimina la fila tres de Sheet1.
Worksheets("Sheet1").Rows(3).Delete
En este ejemplo se eliminan las filas de la regin actual de la hoja de clculo uno
en las que el valor de la celda uno de la fila es el mismo que el valor de la celda
uno de la fila anterior.
For Each rw In Worksheets(1).Cells(1, 1).CurrentRegion.Rows
this = rw.Cells(1, 1).Value
If this = last Then rw.Delete
last = this
Next
Observaciones
Al definir un rango de celdas con el contenido de un archivo de hoja de clculo
XML, slo se usan los valores de la primera hoja del libro. No se puede definir
un rango de celdas no contiguas en formato de hoja de clculo XML.
Ejemplo
En este ejemplo se establece el valor de la celda A1 de Sheet1 como 3.14159.
Else
Worksheets("Sheet1").Range("A1").Value = 3.14159
i = 1
For Each a In Selection.Areas
MsgBox "Area " & i & " of the selection contains " & _
a.Rows.Count & " rows."
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 cdigo sustituye el valor por 0.
For Each c in Worksheets("Sheet1").Range("A1:D10")
i = i + 1
Next a
c.Value = 0
End If
End If
Next c
Propiedad Range.Value
Devuelve o establece un valor de tipo Variant que representa el valor del rango
especificado.
Sintaxis
Sintaxis
expresin .Value(RangeValueDataType)
Parmetros
Nombre
RangeValueDataType
Descripcin
Opcional
Observaciones
La nica diferencia que hay entre esta propiedad y la propiedad Value es
que Value2 no utiliza los tipos de datos Currency y Date. Puede devolver
valores que tengan el formato de estos tipos de datos como nmeros de punto
flotante usando el tipo de datos Double.
Ejemplo
En este ejemplo se utiliza la propiedad Value2 para sumar los valores de dos
celdas.
Sintaxis
Sintaxis
expresin .Width
expresin Variable que representa un objeto Range.
Ejemplo
expresin .Worksheet
Ejemplo
Este ejemplo muestra el nombre de la hoja de clculo que contiene la celda
activa. El ejemplo debe ejecutarse desde una hoja de clculo.
MsgBox ActiveCell.Worksheet.Name
Sub CentrarImagen()
MsgBox Range("testRange").Worksheet.Name
Application.Windows
A collection of all the Window objects in
Microsoft Excel.
Remarks
The Windows collection for the Application object contains all the windows in
the application, whereas the Windowscollection for the Workbook object
contains only the windows in the specified workbook.
Example
Use the Windows property to return the Windows collection. The following
example cascades all the windows that are currently displayed in Microsoft Excel.
Windows.Arrange arrangeStyle:=xlCascade
Use the NewWindow method to create a new window and add it to the
collection. The following example creates a new window for the active workbook.
ActiveWorkbook.NewWindow
Methods
Properties
Name
Description
Name
Description
Arrange
Application
BreakSideBySide
Ends side-by-side mode if two windows are in side-by-side mode. Returns a Boolean value that
represents whether the method was successful.
CompareSideBySideWith
ResetPositionsSideBySide
Resets the position of two worksheet windows that are being compared side by side.
Count
Creator
Item
Parent
SyncScrollingSideBySide
Sintaxis
expresin .ActiveCell
expresin Variable que representa un objeto Window.
.Italic = True
End With
Sintaxis
Observaciones
Si no se especifica un calificador de objeto, esta propiedad devuelve la celda
activa de la ventana activa.
Celda activa no es lo mismo que seleccin. La celda activa es una sola celda de
la seleccin actual. La seleccin puede contener ms de una celda, pero slo una
es la celda activa.
Todas las expresiones siguientes devuelven la celda activa y son equivalentes:
ActiveCell
Application.ActiveCell
ActiveWindow.ActiveCell
Application.ActiveWindow.ActiveCell
Ejemplo
En este ejemplo se usa un cuadro de mensaje para mostrar el valor de la celda
activa. Puesto que la propiedad ActiveCell produce un error si la hoja activa no
es una hoja de clculo, el ejemplo activa Sheet1 antes de usar la
propiedad ActiveCell.
Worksheets("Sheet1").Activate
MsgBox ActiveCell.Value
expresin .Caption
Observaciones
Cuando establece el nombre, puede usarlo como
coleccin Windows (como se muestra en el ejemplo).
.Bold = True
para
la
Ejemplo
En este ejemplo se establece "Consolidate Balance Sheet" como nombre de la
primera ventana del libro activo. Despus, dicho nombre se usa como ndice de
esa ventana en la coleccin Windows.
ActiveWorkbook.Windows(1).Caption
"Consolidated
Sheet"
ActiveWorkbook.Windows("Consolidated Balance Sheet") _
.ActiveSheet.Calculate
Sintaxis
expresin .Selection
expresin Variable que representa un objeto Window.
Worksheets("Sheet1").Activate
With ActiveCell.Font
ndice
Observaciones
Balance
Propiedad Window.RangeSelection
Devuelve un objeto Range que representa las celdas seleccionadas en la hoja de
clculo en la ventana especificada incluso si un objeto grfico est activa o
seleccionada en la hoja de clculo. Solo lectura.
Sintaxis
Ejemplo
En este ejemplo se borra la seleccin de Sheet1 (siempre que la seleccin sea un
rango de celdas).
Worksheets("Sheet1").Activate
Selection.Clear
expresin .RangeSelection
Observaciones
Si un objeto grfico est seleccionado en una hoja de clculo, la
propiedad Selection devuelve el objeto grfico en lugar de un objeto Range, y
la propiedad RangeSelection devolver el rango de celdas que estaba
seleccionado antes de seleccionar el objeto.
Esta propiedad y la propiedad Selection devuelven valores idnticos cuando se
selecciona un rango (no un objeto grfico) en la hoja de clculo.
Si la hoja activa de la ventana especificada no es una hoja de clculo, esta
propiedad devolver un error.
Ejemplo
Este ejemplo muestra la direccin de las celdas seleccionadas en la hoja de
clculo de la ventana activa.
MsgBox ActiveWindow.RangeSelection.Address
Propiedad Window.ActiveSheet
Devuelve un objeto que representa la hoja activa (la hoja en primer plano) del
libro activo o de la ventana o el libro especificado. Devuelve Nothing si no hay
ninguna hoja activa.
Sintaxis
expresin .ActiveSheet
expresin Variable que representa un objeto Window.
Observaciones
Si no se especifica un calificador de objeto, la propiedad devuelve la hoja activa
del libro activo.
Si un libro aparece en ms de una ventana, es posible que la
propiedad ActiveSheet tenga un valor diferente en cada ventana.
Ejemplo
En este ejemplo se muestra el nombre de la hoja activa.
MsgBox "The name of the active sheet is " & ActiveSheet.Name
Areas Objeto
Coleccin de reas, o bloques de celdas
contiguas, de una seleccin.
Remarks
Theres no singular Area object; individual members of the Areas collection
are Range objects. The Areas collection contains one Range object for each
discrete, contiguous range of cells within the selection. If the selection contains
only one area, the Areas collection contains a single Range object that
corresponds to that selection.
Example
Use the Areas property to return the Areas collection. The following example
clears the current selection if it contains more than one area.
If Selection.Areas.Count <> 1 Then Selection.Clear
Propiedades
Nombre
Descripcin
Application
Count
Creator
Item
Parent
del
objeto
Application.Rows y
Application.Columns
Returns a Range object that represents all the
rows on the active worksheet. If the active
document isnt a worksheet, the Rows property
fails. Read-only Range object.
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.
Syntax
expression .Rows
expression A variable that represents an Application object.
Remarks
Using this property without
using ActiveSheet.Rows.
an
object
qualifier
is
equivalent
to
When applied to a Range object thats a multiple selection, this property returns
rows from only the first area of the range. For example, if the Range object has
two areas A1:B2 and C3:D4
Selection.Rows.Count returns 2, not 4.
To use this property on a range that may contain a multiple selection,
test Areas.Count to determine whether the range is a multiple selection. If it is,
loop over each area in the range, as shown in the third example.
Example
This example deletes row three on Sheet1.
Worksheets("Sheet1").Rows(3).Delete
This example deletes rows in the current region on worksheet one where the
value of cell one in the row is the same as the value in cell one in the previous
row.
For Each rw In Worksheets(1).Cells(1, 1).CurrentRegion.Rows
this = rw.Cells(1, 1).Value
If this = last Then rw.Delete
last = this
Next
This example displays the number of rows in the selection on Sheet1. If more
than one area is selected, the example loops through each area.
Worksheets("Sheet1").Activate
areaCount = Selection.Areas.Count
If areaCount <= 1 Then
The following table illustrates some row and column references using the Rows
and Columns properties.
Reference
Meaning
i = i + 1
Rows(1)
Row one
Rows
Columns(1)
Column one
Syntax
Columns("A")
Column one
expression .Columns
expression A variable that represents an Application object.
Columns
Next a
End If
Remarks
Using this property without
using ActiveSheet.Columns.
an
object
qualifier
is
equivalent
to
To work with several rows or columns at the same time, create an object
variable and use the Union method, combining multiple calls to the Rows or
Columns property. The following example changes the format of rows one,
three, and five on worksheet one in the active workbook to bold.
Sub SeveralRows()
Worksheets("Sheet1").Activate
Dim myUnion As Range
Set myUnion = Union(Rows(1), Rows(3), Rows(5))
myUnion.Font.Bold = True
End Sub
Sub Delete_Empty_Rows()
'The range from which to delete the rows.
Dim rnSelection As Range
Sub Delete_Empty_Columns()
'The range from which to delete the columns.
Dim rnSelection As Range
lnDeletedColumns = 0
and
that
the
range
is
and
that
the
range
is
End Sub
End Sub
Application.Cells
Syntax
expression .Cells
expression A variable that represents an Application object.
Remarks
Because the Item property is the default property for the Range object, you can
specify the row and column index immediately after the Cells keyword. For more
information, see the Item property and the examples for this topic.
Using this property without an object qualifier returns a Range object that
represents all the cells on the active worksheet.
Example
This example looks at data in each row and inserts a blank row each time the
value in column A changes.
Sub ChangeInsertRows()
Application.ScreenUpdating = False
Dim xRow As Long
For xRow = Application.Cells(Rows.Count, 1).End(xlUp).Row
To 3 Step -1
If Application.Cells(xRow, 1).Value <>
Application.Cells(xRow - 1, 1).Value Then
Rows(xRow).Resize(1).Insert
Next xRow
Application.ScreenUpdating = True
End Sub
Another easy way to loop through a range is to use a For Each...Next loop with
the collection of cells specified in the Range property. Visual Basic automatically
sets an object variable for the next cell each time the loop runs. The following
procedure loops through the range A1:D10, setting to 0 (zero) any number
whose absolute value is less than 0.01.
Sub RoundToZero2()
For Each c In Worksheets("Sheet1").Range("A1:D10").Cells
If Abs(c.Value) < 0.01 Then c.Value = 0
Next
End Sub
If you do not know the boundaries of the range you want to loop through, you
can use the CurrentRegion property to return the range that surrounds the active
cell. For example, the following procedure, when run from a worksheet, loops
through the range that surrounds the active cell, setting to 0 (zero) any number
whose absolute value is less than 0.01.
Sub RoundToZero3()
For Each c In ActiveCell.CurrentRegion.Cells
If Abs(c.Value) < 0.01 Then c.Value = 0
Next
End Sub
Comments Collection
Methods
Name
Item
Description
Returns a single object from a collection.
Properties
Name
Description
Application
Count
Creator
Parent
Remarks
Each comment is represented by a Comment object.
Example
Use the Comments property to return the Comments collection. The following
example hides all the comments on worksheet one.
Set cmt = Worksheets(1).Comments
For Each c In cmt
c.Visible = False
Next
Comment Object
Comment Object
Remarks
The Comment object is a member of the Comments collection.
Example
Use the Comment property to return a Comment object. The following
example changes the text in the comment in cell E5.
Worksheets(1).Range("E5").Comment.Text "reviewed on " & Date
Methods
Properties
Name
Name
Description
Delete
Next
Previous
Text
Description
Application
Author
Creator
Parent
Shape
Visible