Excel 2007VBA
Excel 2007VBA
Excel 2007VBA
www.sanketham.tkk
Welcome to the Microsoft Office Excel 2007 Developer Reference
This reference contains conceptual overviews, programming tasks, samples, and references to guide you in developing
solutions based on Excel.
Press <Alt > < F11 > to view Visual Basic Window
OR Right Click on Sheet tab and click “View Code”
The Item property returns a single object from a collection. The following example sets the firstBook variable to a
Workbook object that represents workbook one.
The Item property is the default property (default property: A property that you can set for a control so that each time a
new control of that type is created, this property will have the same value.) for most collections, so you can write the same
statement more concisely by omitting the Item keyword.
For more information about a specific collection, see the Help topic for that collection or the Item property for the
collection.
Named Objects
Although you can usually specify an integer value with the Item property, it may be more convenient to return an object by
name. Before you can use a name with the Item property, you must name the object. Most often, this is done by setting
the object's Name property. The following example creates a named worksheet in the active workbook and then refers to
the worksheet by name.
The following example sets the bottom border of cells A1:G1 on Sheet1 to a double line.
Worksheets("Sheet1").Range("A1:A1"). _
Borders.Item(xlEdgeBottom).LineStyle = xlDouble
SolverAdd Function
Adds a constraint to the current problem. Equivalent to clicking Solver in the Data | Analysis group and then clicking Add
in the Solver Parameters dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
CellRef Required Variant. A reference to a cell or a range of cells that forms the left side of a constraint.
Relation Required Integer. The arithmetic relationship between the left and right sides of the constraint. If you choose 4
or 5, CellRef must refer to adjustable (changing) cells, and FormulaText should not be specified.
1 <=
2 =
3 >=
4 Cells referenced by CellRef must have final values that are integers.
5 Cells referenced by CellRef must have final values of either 0 (zero) or 1.
FormulaText Optional Variant. The right side of the constraint.
Remarks
After constraints are added, you can manipulate them with the SolverChange and SolverDelete functions.
Example
This example uses the Solver functions to maximize gross profit in a business problem. The SolverAdd function is used to
add three constraints to the current problem.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK setCell:=Range("TotalProfit"), _
maxMinVal:=1, _
byChange:=Range("C4:E6")
SolverAdd cellRef:=Range("F4:F6"), _
relation:=1, _
formulaText:=100
SolverAdd cellRef:=Range("C4:E6"), _
relation:=3, _
formulaText:=0
SolverAdd cellRef:=Range("C4:E6"), _
relation:=4
SolverSolve userFinish:=False
SolverSave saveArea:=Range("A33")
SolverChange Function
Changes an existing constraint. Equivalent to clicking Solver in the Data | Analysis group and then clicking Change in
the Solver Parameters dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
CellRef Required Variant. A reference to a cell or a range of cells that forms the left side of a constraint.
Relation Required Integer. The arithmetic relationship between the left and right sides of the constraint. If you choose 4
or 5, CellRef must refer to adjustable (changing) cells, and FormulaText should not be specified.
1 <=
2 =
3 >=
4 Cells referenced by CellRef must have final values that are integers.
5 Cells referenced by CellRef must have final values of either 0 (zero) or 1.
FormulaText Optional Variant. The right side of the constraint.
Remarks
If CellRef and Relation do not match an existing constraint, you must use the SolverDelete and SolverAdd functions to
change the constraint.
Example
This example loads the previously calculated Solver model stored on Sheet1, changes one of the constraints, and then
solves the model again.
Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverChange cellRef:=Range("F4:F6"), _
relation:=1, _
formulaText:=200
SolverSolve userFinish:=False
SolverDelete Function
Deletes an existing constraint. Equivalent to clicking Solver in the Data | Analysis group and then clicking Delete in the
Solver Parameters dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverDelete(CellRef, Relation, FormulaText)
CellRef Required Variant. A reference to a cell or a range of cells that forms the left side of a constraint.
Relation Required Integer. The arithmetic relationship between the left and right sides of the constraint. If you choose 4
or 5, CellRef must refer to adjustable (changing) cells, and FormulaText should not be specified.
1 <=
2 =
3 >=
4 Cells referenced by CellRef must have final values that are integers.
5 Cells referenced by CellRef must have final values of either 0 (zero) or 1.
FormulaText Optional Variant. The right side of the constraint.
Example
This example loads the previously calculated Solver model stored on Sheet1, deletes one of the constraints, and then solves
the model again.
Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverDelete cellRef:=Range("C4:E6"), _
relation:=4
SolverSolve userFinish:=False
SolverFinish Function
Tells Microsoft Office Excel what to do with the results and what kind of report to create when the solution process is
completed.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverFinish(KeepFinal, ReportArray)
KeepFinal Optional Variant. Can be either 1 or 2. If KeepFinal is 1 or omitted, the final solution values are kept in the
changing cells, replacing any former values. If KeepFinal is 2, the final solution values are discarded, and the former
values are restored.
ReportArray Optional Variant. The kind of report that Excel will create when Solver is finished: 1 creates an answer
report, 2 creates a sensitivity report, and 3 creates a limit report. Use the Array function to specify the reports you want to
display — for example, ReportArray:= Array(1,3).
Example
This example loads the previously calculated Solver model stored on Sheet1, solves the model again, and then generates an
answer report on a new worksheet.
Worksheets("Sheet1").Activate
SolverLoad LoadArea:=Range("A33:A38")
SolverSolve UserFinish:=True
SolverFinish KeepFinal:=1, ReportArray:=Array(1)
SolverFinishDialog Function
Tells Microsoft Office Excel what to do with the results and what kind of report to create when the solution process is
completed. Equivalent to the SolverFinish function, but also displays the Solver Results dialog box after solving a
problem.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverFinishDialog(KeepFinal, ReportArray)
KeepFinal Optional Variant. Can be either 1 or 2. If KeepFinal is 1 or omitted, the final solution values are kept in the
changing cells, replacing any former values. If KeepFinal is 2, the final solution values are discarded, and the former
values are restored.
ReportArray Optional Variant. The kind of report that Excel will create when Solver is finished: 1 creates an answer
report, 2 creates a sensitivity report, and 3 creates a limit report. Use the Array function to specify the reports you want to
display — for example, ReportArray:= Array(1,3).
Example
This example loads the previously calculated Solver model stored on Sheet1, solves the model again, and then displays the
Finish dialog box with two preset options.
Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverSolve userFinish:=True
SolverFinishDialog keepFinal:=1, reportArray:=Array(1)
SolverGet Function
Returns information about current settings for Solver. The settings are specified in the Solver Parameters and Solver
Options dialog boxes.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverGet(TypeNum, SheetName)
TypeNum Required Integer. A number specifying the type of information you want. The following settings are specified
in the Solver Parameters dialog box.
TypeNum Returns
1 The reference in the Set Target Cell box, or the #N/A error value if Solver has not been used on the active sheet.
2 A number corresponding to the Equal To option: 1 represents Max, 2 represents Min, and 3 represents Value Of.
3 The value in the Value Of box.
4 The reference (as a multiple reference, if necessary) in the By Changing Cells box.
5 The number of constraints.
6 An array of the left sides of the constraints, in text form.
An array of numbers corresponding to the relationships between the left and right sides of the constraints: 1 represents <=, 2
7
represents =, 3 represents >=, 4 represents int, and 5 represents bin.
8 An array of the right sides of the constraints, in text form.
The following settings are specified in the Solver Options dialog box.
TypeNum Returns
15 True if the Use Automatic Scaling check box is selected; False if it is cleared.
16 A number corresponding to the type of estimates: 1 represents Tangent, and 2 represents Quadratic.
17 A number corresponding to the type of derivatives: 1 represents Forward, and 2 represents Central.
18 A number corresponding to the type of search: 1 represents Newton, and 2 represents Conjugate.
19 The convergence value.
Example
This example displays a message if you have not used Solver on Sheet1.
Worksheets("Sheet1").Activate
state = SolverGet(TypeNum:=1)
If IsError(State) Then
MsgBox "You have not used Solver on the active sheet"
End If
SolverLoad Function
Loads existing Solver model parameters that have been saved to the worksheet.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverLoad(LoadArea)
LoadArea Required Variant. A reference on the active worksheet to a range of cells from which you want to load a
complete problem specification. The first cell in the LoadArea contains a formula for the Set Target Cell box in the
Solver Parameters dialog box; the second cell contains a formula for the By Changing Cells box; subsequent cells
contain constraints in the form of logical formulas. The last cell optionally contains an array of Solver option values. For
more information, see SolverOptions. The range represented by the argument LoadArea can be on any worksheet, but
you must specify the worksheet if it is not the active sheet. For example, SolverLoad("Sheet2!A1:A3") loads a
model from Sheet2 even if it is not the active sheet.
Example
This example loads the previously calculated Solver model stored on Sheet1, changes one of the constraints, and then
solves the model again.
Worksheets("Sheet1").Activate
SolverLoad loadArea:=Range("A33:A38")
SolverChange cellRef:=Range("F4:F6"), _
relation:=1, _
formulaText:=200
SolverSolve userFinish:=False
SolverOk Function
Defines a basic Solver model. Equivalent to clicking Solver in the Data | Analysis group and then specifying options in the
Solver Parameters dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SetCell Optional Variant. Refers to a single cell on the active worksheet. Corresponds to the Set Target Cell box in the
Solver Parameters dialog box.
MaxMinVal Optional Variant. Corresponds to the Max, Min, and Value options in the Solver Parameters dialog box.
MaxMinVal Specifies
1 Maximize
2 Minimize
3 Match a specific value
ValueOf Optional Variant. If MaxMinVal is 3, you must specify the value to which the target cell is matched.
ByChange Optional Variant. The cell or range of cells that will be changed so that you will obtain the desired result in
the target cell. Corresponds to the By Changing Cells box in the Solver Parameters dialog box.
Example
This example uses the Solver functions to maximize gross profit in a business problem. The SolverOK function defines a
problem by specifying the SetCell, MaxMinVal, and ByChange arguments.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions precision:=0.001
SolverOK SetCell:=Range("TotalProfit"), _
MaxMinVal:=1, _
ByChange:=Range("C4:E6")
SolverAdd CellRef:=Range("F4:F6"), _
Relation:=1, _
FormulaText:=100
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=3, _
FormulaText:=0
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=4
SolverSolve UserFinish:=False
SolverSave SaveArea:=Range("A33")
SolverOkDialog Function
Same as the SolverOK function, but also displays the Solver dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SetCell Optional Variant. Refers to a single cell on the active worksheet. Corresponds to the Set Target Cell box in the
Solver Parameters dialog box.
MaxMinVal Optional Variant. Corresponds to the Max, Min, and Value options in the Solver Parameters dialog box.
MaxMinVal Specifies
1 Maximize
2 Minimize
3 Match a specific value
ValueOf Optional Variant. If MaxMinVal is 3, you must specify the value that the target cell is matched to.
ByChange Optional Variant. The cell or range of cells that will be changed so that you will obtain the desired result in
the target cell. Corresponds to the By Changing Cells box in the Solver Parameters dialog box.
Example
This example loads the previously calculated Solver model stored on Sheet1, resets all Solver options, and then displays the
Solver Parameters dialog box. From this point on, you can use Solver manually.
Worksheets("Sheet1").Activate
SolverLoad LoadArea:=Range("A33:A38")
SolverReset
SolverOKDialog SetCell:=Range("TotalProfit")
SolverSolve UserFinish:=False
SolverOptions Function
Allows you to specify advanced options for your Solver model. This function and its arguments correspond to the options in
the Solver Options dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
Example
This example sets the Precision option to .001.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions Precision:=0.001
SolverOK SetCell:=Range("TotalProfit"), _
MaxMinVal:=1, _
ByChange:=Range("C4:E6")
SolverAdd CellRef:=Range("F4:F6"), _
Relation:=1, _
FormulaText:=100
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=3, _
FormulaText:=0
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=4
SolverSolve UserFinish:=False
SolverSave SaveArea:=Range("A33")
SolverReset Function
Resets all cell selections and constraints in the Solver Parameters dialog box and restores all the settings in the Solver
Options dialog box to their defaults. Equivalent to clicking Reset All in the Solver Parameters dialog box. The
SolverReset function is called automatically when you call the SolverLoad function.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverReset( )
Example
This example resets the Solver settings to their defaults before defining a new problem.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions Precision:=0.001
SolverOK SetCell:=Range("TotalProfit"), _
MaxMinVal:=1, _
ByChange:=Range("C4:E6")
SolverAdd CellRef:=Range("F4:F6"), _
Relation:=1, _
FormulaText:=100
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=3, _
FormulaText:=0
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=4
SolverSolve UserFinish:=False
SolverSave SaveArea:=Range("A33")
SolverSave Function
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverSave(SaveArea)
SaveArea Required Variant. The range of cells where the Solver model is to be saved. The range represented by the
SaveArea argument can be on any worksheet, but you must specify the worksheet if it is not the active sheet. For
example, SolverSave("Sheet2!A1:A3") saves the model on Sheet2 even if Sheet2 is not the active sheet.
Example
This example uses the Solver functions to maximize gross profit in a business problem. The SolverSave function saves the
current problem to a range on the active worksheet.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions Precision:=0.001
SolverOK SetCell:=Range("TotalProfit"), _
MaxMinVal:=1, _
ByChange:=Range("C4:E6")
SolverAdd CellRef:=Range("F4:F6"), _
Relation:=1, _
FormulaText:=100
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=3, _
FormulaText:=0
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=4
SolverSolve UserFinish:=False
SolverSave SaveArea:=Range("A33")
SolverSolve Function
Begins a Solver solution run. Equivalent to clicking Solve in the Solver Parameters dialog box.
Before you use this function, you must establish a reference to the Solver add-in. In the Visual Basic Editor, with a module
active, click References on the Tools menu, and then select the Solver.xlam check box under Available References. If
Solver.xlam does not appear under Available References, click Browse and open Solver.xlam in the
\office12\library\Solver subfolder.
SolverSolve(UserFinish, ShowRef)
UserFinish Optional Variant.True to return the results without displaying the Solver Results dialog box. False or
omitted to return the results and display the Solver Results dialog box.
ShowRef Optional Variant. Used only if True is passed to the StepThru argument of the SolverOptions function. You
can pass the name of a macro (as a string) as the ShowRef argument. This macro is then called whenever Solver returns
an intermediate solution.
Example
This example uses the Solver functions to maximize gross profit in a business problem. The SolverSolve function begins
the Solver solution run.
Worksheets("Sheet1").Activate
SolverReset
SolverOptions Precision:=0.001
SolverOK SetCell:=Range("TotalProfit"), _
MaxMinVal:=1, _
ByChange:=Range("C4:E6")
SolverAdd CellRef:=Range("F4:F6"), _
Relation:=1, _
FormulaText:=100
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=3, _
FormulaText:=0
SolverAdd CellRef:=Range("C4:E6"), _
Relation:=4
SolverSolve UserFinish:=False
SolverSave SaveArea:=Range("A33")
SQLBind Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLBind and the other ODBC functions in the Xlodbc.xla add-in.
SQLBind specifies where results are placed when they’re retrieved with SQLRetrieve or SQLRetrieveToFile. Use
SQLBind to change the column order of the result set from a query, or to place the result set columns in nonadjacent
worksheet columns.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
Return Value
This function returns an array that lists the bound columns for the current connection, by column number.
If SQLBind is unable to bind the column to the cell in the specified reference, it returns Error 2042.
If ConnectionNum is not valid or if you try to bind a cell that is unavailable, SQLBind returns Error 2015.
If Reference refers to more than a single cell, SQLBind returns Error 2023.
If SQLRetrieve does not have a destination parameter, SQLBind places the result set in the location indicated by
Reference.
Remarks
SQLBind tells the ODBC Control Panel Administrator where to place results when they are received by way of
SQLRetrieve The results are placed in the reference cell and the cells immediately below it.
Use SQLBind if you want the results from different columns to be placed in disjoint worksheet areas.
Use SQLBind for each column in the result set. A binding remains valid as long as the connection specified by
ConnectionNum is open.
Call SQLBind after you call SQLOpen and SQLExecQuery, but before you call SQLRetrieve or SQLRetrieveToFile.
Calls to SQLBind do not affect results that have already been retrieved.
Example
This example runs a query on the Northwind database, and then it uses the SQLBind function to display only the fourth
and ninth columns of the query result set (the product name and the quantity on order) on Sheet1.
databaseName = "Northwind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output1 = Worksheets("Sheet1").Range("A1")
Set output2 = Worksheets("Sheet1").Range("B1")
SQLBind chan, 4, output1
SQLBind chan, 9, output2
SQLRetrieve chan
SQLClose chan
SQLClose Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLClose and the other ODBC functions in the Xlodbc.xla add-in.
SQLClose closes a connection to an external data source.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
SQLClose(ConnectionNum)
ConnectionNum Required. The unique connection ID of the data source you want to disconnect from.
Return Value
If the connection is successfully closed, this function returns 0 (zero) and the connection ID is no longer valid.
If SQLClose is unable to disconnect from the data source, it returns Error 2042.
Example
This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products
that are currently on order.
databaseName = "Northwind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan
SQLError Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLError and the other ODBC functions in the Xlodbc.xla add-in.
SQLError returns detailed error information when it’s called after one of the other ODBC functions fails. If SQLError itself
fails, it cannot return error information.
Error information is defined and stored in memory whenever an ODBC function fails. To make the error information
available, call the SQLError function.
SQLError provides detailed error information only about errors that occur when an ODBC function fails. It does not provide
information about Microsoft Excel errors.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
SQLError()
Return Value
If there are errors, SQLError returns detailed error information in a two-dimensional array in which each row describes one
error.
Each row has the following three fields for information obtained through the SQLError function call in ODBC:
A character string that indicates the ODBC error class and subclass
A numeric value that indicates the data source native error code.
A text message that describes the error.
If a function call generates multiple errors, SQLError creates a row for each error.
If there are no errors from a previous ODBC function call, this function returns only Error 2042.
Example
This example generates an intentional error by attempting to open a connection to the Northwind database by using an
incorrect connection string (Northwind is misspelled). The error information is displayed on Sheet1.
chan = SQLOpen("DSN=Nortwind")
returnArray = SQLError()
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
Worksheets("Sheet1").Cells(1, i).Formula = returnArray(i)
Next i
SQLClose chan
SQLExecQuery Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLOpen and the other ODBC functions in the Xlodbc.xla add-in.
SQLExecQuery executes a query on a data source with a connection that has been established with SQLOpen.
SQLExecQuery executes only the query. Use SQLRetrieve or SQLRetrieveToFile to get the results.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
SQLExecQuery(ConnectionNum, QueryText)
ConnectionNum Required. The unique connection ID returned by SQLOpen that identifies the data source you want to
query.
QueryText Required. The query to be executed on the data source. The query must follow the SQL syntax guidelines for
the specific driver.
Return Value
The value returned by SQLExecQuery depends on the SQL statement, as shown in the following table.
If SQLExecQuery is unable to execute the query on the specified data source, it returns Error 2042.
If you call SQLExecQuery using a previously used connection ID, any pending results on that connection are replaced by
the new results.
Example
This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products
that are currently on order.
databaseName = "Northwind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan
SQLGetSchema Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLGetSchema and the other ODBC functions in the Xlodbc.xla add-in.
SQLGetSchema returns information about the structure of the data source on a particular connection.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
ConnectionNum Required. The unique connection ID of the data source you connected to by using SQLOpen and for
which you want information.
TypeNum Required. Specifies the type of information you want returned, as shown in the following table.
Value Meaning
4 A list of tables for a given owner and database on the current connection.
A list of columns in a particular table and their ODBC SQL data types, in a two-dimensional array. The first field contains the name
5
of the column; the second field is the column’s ODBC SQL data type.
6 The user ID of the current user.
7 The name of the current database.
8 The name of the data source defined during setup or defined by using the ODBC Control Panel Administrator.
9 The name of the DBMS that the data source uses. For example, ORACLE or SQL Server.
10 The server name for the data source.
11 The terminology used by the data source to refer to the owners. For example "owner", "Authorization ID", or "Schema".
12 The terminology used by the data source to refer a table For example, "table" or "file".
13 The terminology used by the data source to refer to a qualifier. For example, "database" or "folder".
The terminology used by the data source to refer to a procedure. For example, "database procedure", "stored procedure", or
14
"procedure".
QualifierText Optional. Included only for the TypeNum values 3, 4, and 5. A string that qualifies the search, as shown in
the following table.
TypeNum QualifierText
The name of the database in the current data source. SQLGetSchema returns the names of the table owners in that
3
database.
Both a database name and an owner name. The syntax consists of the database name followed by the owner's name, with a
4 period separating the two; for example, "DatabaseName.OwnerName". This function returns an array of table names that are
located in the given database and owned by the given owner.
5 The name of a table. SQLGetSchema returns information about the columns in the table.
Return Value
The return value from a successful call to SQLGetSchema depends on the type of information that’s requested.
Remarks
SQLGetSchema uses the ODBC API functions SQLGetInfo and SQLTables to find the requested information.
Example
This example retrieves the database name and DBMS name for the Northwind database and then displays these names in a
message box.
databaseName = "Northwind"
chan = SQLOpen("DSN=" & databaseName)
dsName = SQLGetSchema(chan, 8)
dsDBMS = SQLGetSchema(chan, 9)
MsgBox "Database name is " & dsName & ", and its DBMS is " & dsDBMS
SQLClose chan
SQLOpen Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLOpen and the other ODBC functions in the Xlodbc.xla add-in.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
Value Meaning
The driver dialog box is displayed only if information provided by the connection string and the data source specification aren’t
2
sufficient to complete the connection. All dialog box options are available.
3 The same as 2 except that dialog box options that aren’t required are dimmed (unavailable).
4 The driver dialog box isn’t displayed. If the connection isn’t successful, SQLOpen returns an error.
Return Value
If successful, SQLOpen returns a unique connection ID number. Use the connection ID number with the other ODBC
functions.
If SQLOpen is unable to connect using the information you provide, it returns Error 2042. Additional error information is
placed in memory for use by SQLError.
Example
This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products
that are currently on order.
DatabaseName = "Northwind"
QueryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
Chan = SQLOpen("DSN=" & DatabaseName)
SQLExecQuery Chan, QueryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve Chan, Output, , , True
SQLClose Chan
SQLRequest Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLRequest and the other ODBC functions in the Xlodbc.xla add-in.
SQLRequest connects to an external data source and runs a query from a worksheet, and then it returns the result of the
query as an array.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
Value Meaning
The driver dialog box is displayed only if information provided by the connection string and the data source specification is not
2
sufficient to complete the connection. All dialog box options are available.
The driver dialog box is displayed only if information provided by the connection string and the data source specification is not
3
sufficient to complete the connection. Dialog box options that aren’t required are dimmed (unavailable).
4 The dialog box isn’t displayed. If the connection is not successful, it returns an error.
ColNamesLogical Optional. True to have the column names returned as the first row of results. False to not have the
column names returned. If ColNamesLogical is omitted, the default value is False.
Remarks
The arguments to the SQLRequest function are in a different order than the arguments to the SQL.REQUEST macro
function.
Return Value
If this function completes all of its actions, it returns an array of query results or the number of rows affected by the query.
If SQLRequest is unable to complete all of its actions, it returns an error value and places the error information in memory
for SQLError.
If SQLRequest is unable to access the data source using connectionStr, it returns Error 2042.
Example
This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products
that are currently on order. The SQLRequest function also writes the full connection string to Sheet2.
databaseName = "Northwind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
returnArray = SQLRequest("DSN=" & databaseName, _
queryString, _
Worksheets("Sheet1").Range("A1"), _
2, True)
For i = LBound(returnArray, 1) To UBound(returnArray, 1)
For j = LBound(returnArray, 2) To UBound(returnArray, 2)
Worksheets("Sheet1").Cells(i, j).Formula = _
returnArray(i, j)
Next j
Next i
SQLRetrieve Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLRetrieve and the other ODBC functions in the Xlodbc.xla add-in.
SQLRetrieve retrieves all or part of the results from a previously executed query.
Before using SQLRetrieve, you must establish a connection with SQLOpen, execute a query with SQLExecQuery, and
have the results pending.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (on the Tools menu) in the Visual Basic Editor.
DestinationRef Optional. A Range object that specifies where the results should be placed. This function overwrites any
values in the cells, without confirmation. If DestinationRef refers to a single cell, SQLRetrieve returns all the pending
results in that cell and in the cells to the right of and below it. If DestinationRef is omitted, the bindings established by
previous calls to SQLBind are used to return results. If no bindings exist for the current connection, SQLRetrieve returns
Error 2023. If a particular result column hasn’t been bound and DestinationRef is omitted, the results are discarded.
MaxColumns Optional. The maximum number of columns returned to the worksheet, starting at DestinationRef. If
MaxColumns specifies more columns than are available in the result, SQLRetrieve places data in the columns for which
data is available and clears the additional columns. If MaxColumns specifies fewer columns than are available in the result,
SQLRetrieve discards the rightmost result columns until the results fit the specified size. The order in which the data
source returns the columns determines column position. If MaxColumns is omitted, all the results are returned.
MaxRows Optional. The maximum number of rows to be returned to the worksheet, starting at DestinationRef. If
MaxRows specifies more rows than are available in the results, SQLRetrieve places data in the rows for which data is
available and clears the additional rows. If MaxRows specifies fewer rows than are available in the results, SQLRetrieve
places data in the selected rows but doesn’t discard the additional rows. You can retrieve extra rows by using SQLRetrieve
again and setting FetchFirstLogical to False. If MaxRows is omitted, all the rows in the results are returned.
ColNamesLogical Optional. True to have the column names be returned as the first row of results. False or omitted to
have the column names not be returned.
RowNumsLogical Optional. Used only when DestinationRef is included in the function call. True to have the first
column in the result set contain row numbers. False or omitted to have the row numbers not be returned. You can also
retrieve row numbers by binding column 0 (zero) with SQLBind.
NamedRngLogical Optional. True to have each column of the results be declared as a named range on the worksheet.
The name of each range is the resulting column name. The named range includes only the rows that are returned with
SQLRetrieve. The default value is False.FetchFirstLogicall Optional. Allows you to request results from the beginning of
the result set. If FetchFirstLogical is False, SQLRetrieve can be called repeatedly to return the next set of rows until all
the result rows have been returned. When there are no more rows in the result set, SQLRequest returns 0 (zero). If you
want to retrieve results from the beginning of the result set, set FetchFirstLogical to True. To retrieve additional rows
from the result set, set FetchFirstLogical to False in subsequent calls. The default value is False.
Return Value
SQLRetrieve returns the number of rows in the result set.
If SQLRetrieve is unable to retrieve the results on the specified data source or if there are no results pending, it returns
Error 2042. If no data is found, SQLRetrieve returns 0 (zero).
Remarks
Before calling SQLRetrieve, you must do the following:
1. Establish a connection with a data source by using SQLOpen.
2. Use the connection ID returned in SQLOpen to send a query with SQLExecQuery.
Example
This example runs a query on the Northwind database. The result of the query, displayed on Sheet1, is a list of all products
that are currently on order.
databaseName = "NorthWind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
Set output = Worksheets("Sheet1").Range("A1")
SQLRetrieve chan, output, , , True
SQLClose chan
SQLRetrieveToFile Function
It is recommended that you use the objects, methods, and properties in the Microsoft ActiveX Data Objects (ADO) library
instead of SQLRetrieveToFile and the other ODBC functions in the Xlodbc.xla add-in.
SQLRetrieveToFile retrieves all the results from a previously executed query and places them in a file.
To use this function, you must have established a connection with a data source by using SQLOpen, executed a query by
using SQLExecQuery, and have the results of the query pending.
This function is contained in the Xlodbc.xla add-in. Before you use the function, you must establish a reference to the add-in
by using the References command (in the Tools menu) in the Visual Basic Editor.
ConnectionNum Required. The unique connection ID returned by SQLOpen and for which you have pending query
results that were generated by SQLExecQuery. If ConnectionNum isn’t valid, SQLExecQuery returns Error
2015.Destination Required. A string that specifies the name and path of the file where you want to place the results. If
the file exists, its contents are replaced with the query results. If the file doesn’t exist, SQLRetrieveToFile creates and
opens the file and fills it with the results. The format of the data in the file is compatible with the Microsoft Excel .csv
(comma-separated value) file format. Columns are separated by the character specified by ColumnDelimiter, and the
individual rows are separated by a carriage return. If the file specified by Destination cannot be opened,
SQLRetrieveToFile returns Error 2042.
ColNamesLogical Optional. True to have the column names be returned as the first row of data. False or omitted to
have the column names not be returned.
ColumnDelimiter Optional. A string that specifies the character used to separate the elements in each row. For example,
use "," to specify a comma delimiter, or use ";" to specify a semicolon delimiter. If you omit ColumnDelimiter, the list
separator character is used.
Return Value
If successful, SQLRetrieveToFile returns the query results, writes them to a file, and then returns the number of rows that
were written to the file.
If SQLRetrieveToFile is unable to retrieve the results, it returns Error 2042 and doesn’t write the file.
If there are no pending results on the connection, SQLRetrieveToFile returns Error 2042.
Remarks
Before calling SQLRetrieveToFile, you must do the following:
Example
This example runs a query on the Northwind database. The result of the query, which is a list of all products that are
currently on order, is written as the delimited text file Output.txt in the current folder.
databaseName = "Northwind"
queryString = _
"SELECT * FROM product.dbf WHERE (product.ON_ORDER<>0)"
chan = SQLOpen("DSN=" & databaseName)
SQLExecQuery chan, queryString
SQLRetrieveToFile chan, "OUTPUT.TXT", True
SQLClose chan
To create a workbook in Visual Basic, use the Add method. The following procedure creates a workbook. Microsoft Excel
automatically names the workbook BookN, where N is the next available number. The new workbook becomes the active
workbook.
Sub AddOne()
Workbooks.Add
End Sub
A better way to create a workbook is to assign it to an object variable. In the following example, the Workbook object
returned by the Add method is assigned to an object variable, newBook. Next, several properties of newBook are set.
You can easily control the new workbook by using the object variable.
Sub AddNew()
Set NewBook = Workbooks.Add
With NewBook
.Title = "All Sales"
.Subject = "Sales"
.SaveAs Filename:="Allsales.xls"
End With
End Sub
An index number is a sequential number assigned to a sheet, based on the position of its sheet tab (counting from the left)
among sheets of the same type. The following procedure uses the Worksheets property to activate worksheet one in the
active workbook.
Sub FirstOne()
Worksheets(1).Activate
End Sub
If you want to work with all types of sheets (worksheets, charts, modules, and dialog sheets), use the Sheets property.
The following procedure activates sheet four in the workbook.
Sub FourthOne()
Sheets(4).Activate
End Sub
You can identify sheets by name using the Worksheets and Charts properties. The following statements activate various
sheets in the active workbook.
Worksheets("Sheet1").Activate
Charts("Chart1").Activate
DialogSheets("Dialog1").Activate
You can use the Sheets property to return a worksheet, chart, module, or dialog sheet; the Sheets collection contains all
of these. The following example activates the sheet named "Chart1" in the active workbook.
Sub ActivateChart()
Sheets("Chart1").Activate
End Sub
Opening a Workbook
When you open a workbook using the Open method, it becomes a member of the Workbooks collection. The following
procedure opens a workbook named MyBook.xls located in the folder named MyFolder on drive C.
Sub OpenUp()
Workbooks.Open("C:\MyFolder\MyBook.xls")
End Sub
Saving Documents as Web Pages
In Microsoft Excel, you can save a workbook, worksheet, chart, range, query table, PivotTable report, print area, or
AutoFilter range to a Web page. You can also edit HTML files directly in Excel.
ActiveWorkbook.SaveAs _
Filename:="C:\Reports\myfile.htm", _
FileFormat:=xlHTML
After setting the attributes, you can use the Publish method to save the workbook, worksheet, chart, range, query table,
PivotTable report, print area, or AutoFilter range to a Web page. The following example sets various application-level
properties and then sets the AllowPNG property of the active workbook, overriding the application-level default setting.
Finally, the example saves the range as "C:\Reports\1998_Q1.htm."
With Application.DefaultWebOptions
.RelyonVML = True
.AllowPNG = True
.PixelsPerInch = 96
End With
With ActiveWorkbook
.WebOptions.AllowPNG = False
With .PublishObjects(1)
.FileName = "C:\Reports\1998_Q1.htm"
.Publish
End With
End With
You can also save the files directly to a Web server. The following example saves a range to a Web server, giving the Web
page the URL address http://example.homepage.com/annualreport.htm.
With ActiveWorkbook
With .WebOptions
.RelyonVML = True
.PixelsPerInch = 96
End With
With .PublishObjects(1)
.FileName = _
"http://example.homepage.com/annualreport.htm"
.Publish
End With
End With
Workbooks.Open Filename:="C:\Reports\1997_Q4.htm"
After opening the file, you can customize the appearance, content, browser support, editing support, graphics formats,
screen resolution, file organization, and encoding of the HTML document by setting properties of the DefaultWebOptions
and WebOptions objects.
The following special formatting and Visual Basic for Applications (VBA) codes can be included as a part of the header and
footer properties (LeftHeader, CenterHeader, RightHeader, LeftFooter, CenterFooter, and RightFooter).
Format
Description
code
&"fontname" Prints the characters that follow in the specified font. Be sure to include the double quotation marks.
&nn Prints the characters that follow in the specified font size. Use a two-digit number to specify a size in points.
&color Prints the characters in the specified color. User supplies a hexidecimal color value.
Example
The following code shows how formatting and VBA codes can be used to modify the header information and appearance.
Sub Date_Time()
ActiveSheet.PageSetup.CenterHeader = "&D &B&ITime:&I&B&T"
End Sub
A common task when using Visual Basic is to specify a cell or range of cells and then do something with it, such as enter a
formula or change the format. You can usually do this in one statement that identifies the range and also changes a
property or applies a method.
A Range object in Visual Basic can be either a single cell or a range of cells. The following topics show the most common
ways to identify and work with Range objects.
When you apply the Cells property to a worksheet without specifying an index number, the method returns a Range object
that represents all the cells on the worksheet. The following Sub procedure clears the contents from all the cells on Sheet1
in the active workbook.
Sub ClearSheet()
Worksheets("Sheet1").Cells.ClearContents
End Sub
You can refer to a cell or range of cells in the A1 reference style by using the Range property. The following subroutine
changes the format of cells A1:D5 to bold.
Sub FormatRange()
Workbooks("Book1").Sheets("Sheet1").Range("A1:D5") _
.Font.Bold = True
End Sub
The following table illustrates some A1-style references using the Range property.
Reference Meaning
Range("A1") Cell A1
Range("A1:B5") Cells A1 through B5
Range("C5:D9,G9:H16") A multiple-area selection
Range("A:A") Column A
Range("1:1") Row 1
Range("A:C") Columns A through C
Range("1:5") Rows 1 through 5
Range("1:1,3:3,8:8") Rows 1, 3, and 8
Range("A:A,C:C,F:F") Columns A, C, and F
If you set an object variable to a Range object, you can easily manipulate the range by using the variable name.
The following procedure creates the object variable myRange and then assigns the variable to range A1:D5 on Sheet1 in
the active workbook. Subsequent statements modify properties of the range by substituting the variable name for the
Range object.
Sub Random()
Dim myRange As Range
Set myRange = Worksheets("Sheet1").Range("A1:D5")
myRange.Formula = "=RAND()"
myRange.Font.Bold = True
End Sub
You can use the Cells property to refer to a single cell by using row and column index numbers. This property returns a
Range object that represents a single cell. In the following example, Cells(6,1) returns cell A6 on Sheet1. The Value
property is then set to 10.
Sub EnterValue()
Worksheets("Sheet1").Cells(6, 1).Value = 10
End Sub
The Cells property works well for looping through a range of cells, because you can substitute variables for the index
numbers, as shown in the following example.
Sub CycleThrough()
Dim Counter As Integer
For Counter = 1 To 20
Worksheets("Sheet1").Cells(Counter, 3).Value = Counter
Next Counter
End Sub
How to: Refer to Cells by Using Shortcut Notation
You can use either the A1 reference style or a named range within brackets as a shortcut for the Range property. You do
not have to type the word "Range" or use quotation marks, as shown in the following examples.
Sub ClearRange()
Worksheets("Sheet1").[A1:B5].ClearContents
End Sub
Sub SetValue()
[MyRange].Value = 30
End Sub
Using the appropriate method, you can easily refer to multiple ranges. Use the Range and Union methods to refer to any
group of ranges; use the Areas property to refer to the group of ranges selected on a worksheet.
Sub ClearRanges()
Worksheets("Sheet1").Range("C5:D9,G9:H16,B14:D18"). _
ClearContents
End Sub
Named ranges make it easier to use the Range property to work with multiple ranges. The following example works when
all three named ranges are on the same sheet.
Sub ClearNamed()
Range("MyRange, YourRange, HisRange").ClearContents
End Sub
Sub MultipleRange()
Dim r1, r2, myMultipleRange As Range
Set r1 = Sheets("Sheet1").Range("A1:B2")
Set r2 = Sheets("Sheet1").Range("C3:D4")
Set myMultipleRange = Union(r1, r2)
myMultipleRange.Font.Bold = True
End Sub
Sub FindMultiple()
If Selection.Areas.Count > 1 Then
MsgBox "Cannot do this to a multiple selection."
End If
End Sub
Ranges are easier to identify by name than by A1 notation. To name a selected range, click the name box at the left end of
the formula bar, type a name, and then press ENTER.
Sub FormatRange()
Range("MyBook.xls!MyRange").Font.Italic = True
End Sub
The following example refers to the worksheet-specific range named "Sheet1!Sales" in the workbook named "Report.xls."
Sub FormatSales()
Range("[Report.xls]Sheet1!Sales").BorderAround Weight:=xlthin
End Sub
To select a named range, use the GoTo method, which activates the workbook and the worksheet and then selects the
range.
Sub ClearRange()
Application.Goto Reference:="MyBook.xls!MyRange"
Selection.ClearContents
End Sub
The following example shows how the same procedure would be written for the active workbook.
Sub ClearRange()
Application.Goto Reference:="MyRange"
Selection.ClearContents
End Sub
Sub ApplyColor()
Const Limit As Integer = 25
For Each c In Range("MyRange")
If c.Value > Limit Then
c.Interior.ColorIndex = 27
End If
Next c
End Sub
Use the Rows property or the Columns property to work with entire rows or columns. These properties return a Range
object that represents a range of cells. In the following example, Rows(1) returns row one on Sheet1. The Bold property
of the Font object for the range is then set to True.
Sub RowBold()
Worksheets("Sheet1").Rows(1).Font.Bold = True
End Sub
The following table illustrates some row and column references using the Rows and Columns properties.
Reference Meaning
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
When using Visual Basic, you often need to run the same block of statements on each cell in a range of cells. To do this,
you combine a looping statement and one or more methods to identify each cell, one at a time, and run the operation.
One way to loop through a range is to use the For...Next loop with the Cells property. Using the Cells property, you can
substitute the loop counter (or other variables or expressions) for the cell index numbers. In the following example, the
variable counter is substituted for the row index. The procedure loops through the range C1:C20, setting to 0 (zero) any
number whose absolute value is less than 0.01.
Sub RoundToZero1()
For Counter = 1 To 20
Set curCell = Worksheets("Sheet1").Cells(Counter, 3)
If Abs(curCell.Value) < 0.01 Then curCell.Value = 0
Next Counter
End Sub
Another easy way to loop through a range is to use a For Each...Next loop with the collection of cells 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
When you work with Microsoft Excel, you usually select a cell or cells and then perform an action, such as formatting the
cells or entering values in them. In Visual Basic, it is usually not necessary to select cells before modifying them.
For example, if you want to enter a formula in cell D6 using Visual Basic, you do not need to select the range D6. You just
need to return the Range object and then set the Formula property to the formula you want, as shown in the following
example.
Sub EnterFormula()
Worksheets("Sheet1").Range("D6").Formula = "=SUM(D2:D5)"
End Sub
For examples of using other methods to control cells without selecting them, see How to: Reference Cells and Ranges.
The macro recorder will often create a macro that uses the Select method and the Selection property. The following Sub
procedure was created using the macro recorder, and it illustrates how Select and Selection work together.
Sub Macro1()
Sheets("Sheet1").Select
Range("A1").Select
ActiveCell.FormulaR1C1 = "Name"
Range("B1").Select
ActiveCell.FormulaR1C1 = "Address"
Range("A1:B1").Select
Selection.Font.Bold = True
End Sub
The following example accomplishes the same task without activating or selecting the worksheet or cells.
Sub Labels()
With Worksheets("Sheet1")
.Range("A1") = "Name"
.Range("B1") = "Address"
.Range("A1:B1").Font.Bold = True
End With
End Sub
Sub CopyRow()
Worksheets("Sheet1").Rows(1).Copy
Worksheets("Sheet2").Select
Worksheets("Sheet2").Rows(1).Select
Worksheets("Sheet2").Paste
End Sub
Activating a Cell Within a Selection
You can use the Activate method to activate a cell within a selection. There can be only one active cell, even when a range
of cells is selected. The following procedure selects a range and then activates a cell within the range without changing the
selection.
Sub MakeActive()
Worksheets("Sheet1").Activate
Range("A1:D4").Select
Range("B2").Activate
End Sub
If you are working with the same range on more than one sheet, use the Array function to specify two or more sheets to
select. The following example formats the border of a 3-D range of cells.
Sub FormatSheets()
Sheets(Array("Sheet2", "Sheet3", "Sheet5")).Select
Range("A1:H1").Select
Selection.Borders(xlBottom).LineStyle = xlDouble
End Sub
The following example applies the FillAcrossSheets method to transfer the formats and any data from the range on
Sheet2 to the corresponding ranges on all the worksheets in the active workbook.
Sub FillAll()
Worksheets("Sheet2").Range("A1:H1") _
.Borders(xlBottom).LineStyle = xlDouble
Worksheets.FillAcrossSheets (Worksheets("Sheet2") _
.Range("A1:H1"))
End Sub
The ActiveCell property returns a Range object that represents the cell that is active. You can apply any of the properties
or methods of a Range object to the active cell, as in the following example.
Sub SetValue()
Worksheets("Sheet1").Activate
ActiveCell.Value = 35
End Sub
Note
You can work with the active cell only when the worksheet that it is on is the active sheet.
Moving the Active Cell
You can use the Activate method to designate which cell is the active cell. For example, the following procedure makes B5
the active cell and then formats it as bold.
Sub SetActive()
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Range("B5").Activate
ActiveCell.Font.Bold = True
End Sub
You can insert a cell error value into a cell or test the value of a cell for an error value by using the CVErr function. The cell
error values can be one of the following XlCVError constants.
Example
This example inserts the seven cell error values into cells A1:A7 on Sheet1.
This example displays a message if the active cell on Sheet1 contains a cell error value. You can use this example as a
framework for a cell-error-value error handler.
Worksheets("Sheet1").Activate
If IsError(ActiveCell.Value) Then
errval = ActiveCell.Value
Select Case errval
Case CVErr(xlErrDiv0)
MsgBox "#DIV/0! error"
Case CVErr(xlErrNA)
MsgBox "#N/A error"
Case CVErr(xlErrName)
MsgBox "#NAME? error"
Case CVErr(xlErrNull)
MsgBox "#NULL! error"
Case CVErr(xlErrNum)
MsgBox "#NUM! error"
Case CVErr(xlErrRef)
MsgBox "#REF! error"
Case CVErr(xlErrValue)
MsgBox "#VALUE! error"
Case Else
MsgBox "This should never happen!!"
End Select
End If
To add controls to a document, display the Control Toolbox, click the control you want to add, and then click on the
document. Drag an adjustment handle of the control until the control's outline is the size and shape you want.
To add controls to a user form, find the control you want to add in the Toolbox, drag the control onto the form, and then
drag an adjustment handle on the control until the control's outline is the size and shape you want.
Find the control you want to add in the Toolbox and drag the control onto the form.
Right-click a control in design mode and click Properties to display the Properties window.
You can initialize controls in a procedure before you show a form, or you can add code to the Initialize event of
the form.
All controls have a predefined set of events. For example, a command button has a Click event that occurs
when the user clicks the command button. You can write event procedures that run when the events occur.
6. Displaying a Custom Dialog Box
Some properties can be set at run time. Changes made to the dialog box by the user are lost when the dialog
box is closed.
To create a custom dialog box, you must create a UserForm. To create a UserForm, click UserForm on the Insert menu in
the Visual Basic Editor.
Use the Properties window to change the name, behavior, and appearance of the form. For example, to change the caption
on a form, set the Caption property.
ActiveX Controls
For more information about a specific control, select an object from the following list. For information about events, select a
control and click Events at the top of the topic.
CheckBox
OptionButton
ComboBox
ScrollBar
CommandButton
SpinButton
Image
TextBox
Label
ToggleButton
ListBox
This topic covers specific information about using ActiveX controls on worksheets and chart sheets. For general information
on adding and working with controls, see Using ActiveX Controls on a Document and Creating a Custom Dialog Box.
Keep the following points in mind when you are working with controls on sheets:
In addition to the standard properties available for ActiveX controls, the following properties can be used with
ActiveX controls in Microsoft Excel: BottomRightCell, LinkedCell, ListFillRange, Placement, PrintObject,
TopLeftCell, and ZOrder.
These properties can be set and returned using the ActiveX control name. The following example scrolls the
workbook window so CommandButton1 is in the upper-left corner.
Set t = Sheet1.CommandButton1.TopLeftCell
With ActiveWindow
.ScrollRow = t.Row
.ScrollColumn = t.Column
End With
Some Microsoft Excel Visual Basic methods and properties are disabled when an ActiveX control is activated. For
example, the Sort method cannot be used when a control is active, so the following code fails in a button click
event procedure (because the control is still active after the user clicks it).
You can work around this problem by activating some other element on the sheet before you use the property or
method that failed. For example, the following code sorts the range:
Controls on a Microsoft Excel workbook embedded in a document in another application will not work if the user
double-clicks the workbook to edit it. The controls will work if the user right-clicks the workbook and selects the
Open command from the shortcut menu.
When a Microsoft Excel workbook is saved using the Microsoft Excel 5.0/95 Workbook file format, ActiveX control
information is lost.
The Me keyword in an event procedure for an ActiveX control on a sheet refers to the sheet, not to the control.
Worksheets(1).OLEObjects.Add "Forms.CommandButton.1", _
Left:=10, Top:=10, Height:=20, Width:=100
Sheet1.CommandButton1.Caption = "Run"
Note that when you use a control name outside the class module for the sheet containing the control, you must qualify the
control name with the sheet name.
To change the control name you use in Visual Basic code, select the control and set the (Name) property in the Properties
window.
Because ActiveX controls are also represented by OLEObject objects in the OLEObjects collection, you can set control
properties using the objects in the collection. The following example sets the left position of the control named
"CommandButton1."
Worksheets(1).OLEObjects("CommandButton1").Left = 10
Control properties that are not shown as properties of the OLEObject object can be set by returning the actual control
object using the Object property. The following example sets the caption for CommandButton1.
Worksheets(1).OLEObjects("CommandButton1"). _
Object.Caption = "run me"
Because all OLE objects are also members of the Shapes collection, you can use the collection to set properties for several
controls. The following example aligns the left edge of all controls on worksheet 1.
You use the code name of a control in the names of its event procedures. However, when you return a control from the
Shapes or OLEObjects collection for a sheet, you must use the shape name, not the code name, to refer to the control by
name. For example, assume that you add a check box to a sheet and that both the default shape name and the default
code name are CheckBox1. If you then change the control code name by typing chkFinished next to (Name) in the
Properties window, you must use chkFinished in event procedure names, but you still have to use CheckBox1 to return the
control from the Shapes or OLEObject collection, as shown in the following example.
font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal,
xlDialogActiveCellFont
background, start_char, char_count
xlDialogApplyStyle style_text
xlDialogAppMove x_num, y_num
xlDialogAppSize x_num, y_num
xlDialogArrangeAll arrange_num, active_doc, sync_horiz, sync_vert
xlDialogAssignToObject macro_ref
xlDialogChartSourceData
xlDialogChartTrend type, ord_per, forecast, backcast, intercept, equation, r_squared, name
xlDialogChartType
long, ref, gallery_num, type_num, plot_by, categories, ser_titles, legend, title, x_title, y_title, z_title,
xlDialogChartWizard
number_cats, number_titles
xlDialogCheckboxProperties value, link, accel_text, accel2_text, 3d_shading
xlDialogClear type_num
xlDialogColorPalette file_text
xlDialogColumnWidth width_num, reference, standard, type_num, standard_num
xlDialogCombination type_num
xlDialogConditionalFormatting
xlDialogCustomizeToolbar category
xlDialogCustomViews
xlDialogDataDelete
xlDialogDataLabel show_option, auto_text, show_key
xlDialogDataSeries rowcol, type_num, date_num, step_value, stop_value, trend
xlDialogDataValidation
xlDialogDefineName name_text, refers_to, macro_type, shortcut_text, hidden, category, local
xlDialogDefineStyle style_text, number, font, alignment, border, pattern, protection
xlDialogDefineStyle style_text, attribute_num, additional_def_args, ...
xlDialogDeleteFormat format_text
xlDialogDeleteName name_text
xlDialogDemote row_col
xlDialogDisplay formulas, gridlines, headings, zeros, color_num, reserved, outline, page_breaks, object_num
xlDialogDisplay cell, formula, value, format, protection, names, precedents, dependents, note
xlDialogFillGroup type_num
xlDialogFillWorkgroup type_num
xlDialogFilter
xlDialogFilterAdvanced operation, list_ref, criteria_ref, copy_ref, unique
xlDialogFindFile
xlDialogFont name_text, size_num
font, font_style, size, strikethrough, superscript, subscript, outline, shadow, underline, color, normal,
xlDialogFontProperties
background, start_char, char_count
xlDialogFormatAuto format_num, number, font, alignment, border, pattern, width
layer_num, view, overlap, angle, gap_width, gap_depth, chart_depth, doughnut_size, axis_num, drop,
xlDialogFormatChart
hilo, up_down, series_line, labels, vary
xlDialogFormatCharttype apply_to, group_num, dimension, type_num
color, backgd, apply, name_text, size_num, bold, italic, underline, strike, outline, shadow, object_id,
xlDialogFormatFont
start_num, char_num
xlDialogFormatFont name_text, size_num, bold, italic, underline, strike, color, outline, shadow
name_text, size_num, bold, italic, underline, strike, color, outline, shadow, object_id_text, start_num,
xlDialogFormatFont
char_num
xlDialogFormatLegend position_num
type_num, view, overlap, gap_width, vary, drop, hilo, angle, gap_depth, chart_depth, up_down,
xlDialogFormatMain
series_line, labels, doughnut_size
xlDialogFormatMove x_offset, y_offset, reference
xlDialogFormatMove x_pos, y_pos
xlDialogFormatMove explosion_num
xlDialogFormatNumber format_text
type_num, view, overlap, gap_width, vary, drop, hilo, angle, series_dist, series_num, up_down,
xlDialogFormatOverlay
series_line, labels, doughnut_size
xlDialogFormatSize width, height
xlDialogFormatSize x_off, y_off, reference
xlDialogGallery3dArea type_num
xlDialogGallery3dBar type_num
xlDialogGallery3dColumn type_num
xlDialogGallery3dLine type_num
xlDialogGallery3dPie type_num
xlDialogGallery3dSurface type_num
xlDialogGalleryArea type_num, delete_overlay
xlDialogGalleryBar type_num, delete_overlay
xlDialogGalleryColumn type_num, delete_overlay
xlDialogGalleryCustom name_text
xlDialogInsertHyperlink
xlDialogInsertNameLabel
xlDialogInsertObject object_class, file_name, link_logical, display_icon_logical, icon_file, icon_number, icon_label
xlDialogInsertPicture file_name, filter_number
xlDialogInsertTitle chart, y_primary, x_primary, y_secondary, x_secondary
xlDialogMailNextLetter
xlDialogMainChart type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle
xlDialogMainChartType type_num
xlDialogMenuEditor
xlDialogMove x_pos, y_pos, window_text
xlDialogOptionsListsAdd string_array
xlDialogOptionsListsAdd import_ref, by_row
xlDialogOptionsME def_rtl_sheet, crsr_mvmt, show_ctrl_char, gui_lang
xlDialogOptionsTransition menu_key, menu_key_action, nav_keys, trans_eval, trans_entry
formula, status, notes, show_info, object_num, page_breaks, formulas, gridlines, color_num, headers,
xlDialogOptionsView
outline, zeros, hor_scroll, vert_scroll, sheet_tabs
xlDialogOutline auto_styles, row_dir, col_dir, create_apply
xlDialogOverlay type_num, stack, 100, vary, overlap, drop, hilo, overlap%, cluster, angle, series_num, auto
xlDialogOverlayChartType type_num
head, foot, left, right, top, bot, hdng, grid, h_cntr, v_cntr, orient, paper_size, scale, pg_num,
xlDialogPageSetup
pg_order, bw_cells, quality, head_margin, foot_margin, notes, draft
head, foot, left, right, top, bot, size, h_cntr, v_cntr, orient, paper_size, scale, pg_num, bw_chart,
xlDialogPageSetup
quality, head_margin, foot_margin, draft
xlDialogPageSetup head, foot, left, right, top, bot, orient, paper_size, scale, quality, head_margin, foot_margin, pg_num
xlDialogParse parse_text, destination_ref
xlDialogPasteNames
xlDialogPasteSpecial paste_num, operation_num, skip_blanks, transpose
xlDialogPasteSpecial rowcol, titles, categories, replace, series
xlDialogPasteSpecial paste_num
xlDialogPasteSpecial format_text, pastelink_logical, display_icon_logical, icon_file, icon_number, icon_label
xlDialogPivotCalculatedItem
xlDialogPivotClientServerSet
xlDialogPivotFieldGroup start, end, by, periods
xlDialogPivotFieldProperties name, pivot_field_name, new_name, orientation, function, formats
xlDialogPivotFieldUngroup
xlDialogPivotShowPages name, page_field
xlDialogPivotSolveOrder
xlDialogPivotTableOptions
type, source, destination, name, row_grand, col_grand, save_data, apply_auto_format, auto_page,
xlDialogPivotTableWizard
reserved
xlDialogPlacement placement_type
range_num, from, to, copies, draft, preview, print_what, color, feed, quality, y_resolution, selection,
xlDialogPrint
printer_text, print_to_file, collate
xlDialogPrinterSetup printer_text
xlDialogPrintPreview
xlDialogPromote rowcol
xlDialogProperties title, subject, author, keywords, comments
xlDialogProtectDocument contents, windows, password, objects, scenarios
xlDialogProtectSharing
xlDialogPublishAsWebPage
xlDialogPushbuttonProperties default_logical, cancel_logical, dismiss_logical, help_logical, accel_text, accel_text2
xlDialogReplaceFont font_num, name_text, size_num, bold, italic, underline, strike, color, outline, shadow
xlDialogRoutingSlip recipients, subject, message, route_num, return_logical, status_logical
xlDialogRowHeight height_num, reference, standard_height, type_num
xlDialogSaveWorkspace name_text
xlDialogScale cross, cat_labels, cat_marks, between, max, reverse
xlDialogScale min_num, max_num, major, minor, cross, logarithmic, reverse, max
xlDialogScale cat_labels, cat_marks, reverse, between
xlDialogScenarioMerge source_file
xlDialogScenarioSummary result_ref, report_type
xlDialogScrollbarProperties value, min, max, inc, page, link, 3d_shading
xlDialogSelectSpecial type_num, value_type, levels
xlDialogSendMail recipients, subject, return_receipt
xlDialogSeriesAxes axis_num
xlDialogSeriesOptions
xlDialogSeriesOrder chart_num, old_series_num, new_series_num
xlDialogSeriesShape
xlDialogSeriesX x_ref
xlDialogSortSpecial sort_by, method, key1, order1, key2, order2, key3, order3, header, order, case
xlDialogSplit col_split, row_split
xlDialogStandardFont name_text, size_num, bold, italic, underline, strike, color, outline, shadow
xlDialogStandardWidth standard_num
xlDialogStyle bold, italic
xlDialogVbaInsertFile filename_text
xlDialogVbaMakeAddIn
xlDialogVbaProcedureDefinition
xlDialogView3d elevation, perspective, rotation, axes, height%, autoscale
xlDialogWebOptionsEncoding
xlDialogWebOptionsFiles
xlDialogWebOptionsFonts
xlDialogWebOptionsGeneral
xlDialogWebOptionsPictures
xlDialogWindowMove x_pos, y_pos, window_text
xlDialogWorkbookTabSplit ratio_num
xlDialogWorkbookUnhide sheet_text
xlDialogWorkgroup name_array
fixed, decimals, r1c1, scroll, status, formula, menu_key, remote, entermove, underlines, tools, notes,
xlDialogWorkspace
nav_keys, menu_key_action, drag_drop, show_info
xlDialogZoom magnification
Some control properties can be set and returned while Visual Basic code is running. The following example sets the Text
property of a text box to "Hello."
TextBox1.Text = "Hello"
The data entered on a form by a user is lost when the form is closed. If you return the values of controls on a form after
the form has been unloaded, you get the initial values for the controls rather than the values the user entered.
If you want to save the data entered on a form, you can save the information to module-level variables while the form is
still running. The following example displays a form and saves the form data.
To test your dialog box in the Visual Basic Editor, click Run Sub/UserForm on the Run menu in the Visual Basic Editor.
To display a dialog box from Visual Basic, use the Show method. The following example displays the dialog box named
UserForm1.
Initializing Control Properties
You can initialize controls at run time by using Visual Basic code in a macro. For example, you could fill a list box, set text
values, or set option buttons.
The following example uses the AddItem method to add data to a list box. Then it sets the value of a text box and displays
the form.
You can also use code in the Intialize event of a form to set initial values for controls on the form. An advantage to setting
initial control values in the Initialize event is that the initialization code stays with the form. You can copy the form to
another project, and when you run the Show method to display the dialog box, the controls will be initialized.
Application events occur when a workbook is created or opened, when any sheet in any open workbook changes, or when
any PivotTable is created or opened. To write event procedures for the Application object, you must create a new object
using the WithEvents keyword in a class module. For more information, see Using Events with the Application Object.
NewWorkbook WindowResize
SheetActivate WorkbookActivate
SheetBeforeDoubleClick WorkbookAddinInstall
SheetBeforeRightClick WorkbookAddinUninstall
SheetCalculate WorkbookBeforeClose
SheetChange WorkbookBeforePrint
SheetDeactivate WorkbookBeforeSave
SheetFollowHyperlink WorkbookDeactivate
SheetSelectionChange WorkbookNewSheet
SheetPivotTableUpdate WorkbookOpen
WindowActivate WorkbookPivotTableCloseConnection
WindowDeactivate WorkbookPivotTableOpenConnection
Chart events occur when the user activates or changes a chart. Events on chart sheets are enabled by default. To view the
event procedures for a sheet, right-click the sheet tab and select View Code from the shortcut menu. Select the event
name from the Procedure drop-down list box.
Activate
MouseDown
BeforeDoubleClick
MouseMove
BeforeRightClick
MouseUp
Calculate
Resize
Deactivate
Select
DragOver
SeriesChange
DragPlot
Note
To write event procedures for an embedded chart, you must create a new object using the WithEvents keyword in a class module. For
more information, see Using Events with Embedded Charts.
This example changes a point's border color when the user changes the point value.
After you have added controls to your dialog box or document, you add event procedures to determine how the controls
respond to user actions.
User forms and controls have a predefined set of events. For example, a command button has a Click event that occurs
when the user clicks the command button, and UserForms have an Initialize event that runs when the form is loaded.
To write a control or form event procedure, open a module by double-clicking the form or control, and select the event from
the Procedure drop-down list box.
Event procedures include the name of the control. For example, the name of the Click event procedure for a command
button named Command1 is Command1_Click.
If you add code to an event procedure and then change the name of the control, your code remains in procedures with the
previous name.
For example, assume you add code to the Click event for Commmand1 and then rename the control to Command2. When
you double-click Command2, you will not see any code in the Click event procedure. You will need to move code from
Command1_Click to Command2_Click.
To simplify development, it is a good practice to name your controls before writing code.
Events on sheets are enabled by default. To view the event procedures for a sheet, right-click the sheet tab and click View
Code on the shortcut menu. Select one of the following events from the Procedure drop-down list box.
Activate
Deactivate
BeforeDoubleClick
FollowHyperlink
BeforeRightClick
PivotTableUpdate
Calculate
SelectionChange
Change
Worksheet-level events occur when a worksheet is activated, when the user changes a worksheet cell, or when the
PivotTable changes. The following example adjusts the size of columns A through F whenever the worksheet is recalculated.
Some events can be used to substitute an action for the default application behavior, or to make a small change to the
default behavior. The following example traps the right-click event and adds a new menu item to the shortcut menu for cells
B1:B10.
Worksheet, chart sheet, and workbook event procedures are available for any open sheet or workbook. To write event
procedures for an embedded chart, QueryTable object, or Application object, you must create a new object using the
WithEvents keyword in a class module.
Use the EnableEvents property to enable or disable events. For example, using the Save method to save a workbook
causes the BeforeSave event to occur. You can prevent this by setting the EnableEvents property to False before you call
the Save method.
Example
Application.EnableEvents = False
ActiveWorkbook.Save
Application.EnableEvents = True
You can use most Microsoft Excel worksheet functions in your Visual Basic statements. For a list of the worksheet functions
you can use, see List of Worksheet Functions Available to Visual Basic.
Note
Some worksheet functions are not useful in Visual Basic. For example, the Concatenate function is not needed because in Visual Basic you
can use the & operator to join multiple text values.
The following Sub procedure uses the Min worksheet function to determine the smallest value in a range of cells. First, the
variable myRange is declared as a Range object, and then it is set to range A1:C10 on Sheet1. Another variable,
answer, is assigned the result of applying the Min function to myRange. Finally, the value of answer is displayed in a
message box.
Sub UseFunction()
Dim myRange As Range
Set myRange = Worksheets("Sheet1").Range("A1:C10")
answer = Application.WorksheetFunction.Min(myRange)
MsgBox answer
End Sub
If you use a worksheet function that requires a range reference as an argument, you must specify a Range object. For
example, you can use the Match worksheet function to search a range of cells. In a worksheet cell, you would enter a
formula such as =MATCH(9,A1:A10,0). However, in a Visual Basic procedure, you would specify a Range object to get the
same result.
Sub FindFirst()
myVar = Application.WorksheetFunction _
.Match(9, Worksheets(1).Range("A1:A10"), 0)
MsgBox myVar
End Sub
Note
Visual Basic functions do not use the WorksheetFunction qualifier. A function may have the same name as a Microsoft Excel function and
yet work differently. For example, Application.WorksheetFunction.Log and Log will return different values.
Sub InsertFormula()
Worksheets("Sheet1").Range("A1:B3").Formula = "=RAND()"
End Sub
Example
This example uses the worksheet function Pmt to calculate a home mortgage loan payment. Notice that this example uses
the InputBox method instead of the InputBox function so that the method can perform type checking. The Static
statements cause Visual Basic to retain the values of the three variables; these are displayed as default values the next time
you run the program.
Static loanAmt
Static loanInt
Static loanTerm
loanAmt = Application.InputBox _
(Prompt:="Loan amount (100,000 for example)", _
Default:=loanAmt, Type:=1)
loanInt = Application.InputBox _
(Prompt:="Annual interest rate (8.75 for example)", _
Default:=loanInt, Type:=1)
loanTerm = Application.InputBox _
(Prompt:="Term in years (30 for example)", _
Default:=loanTerm, Type:=1)
payment = Application.WorksheetFunction _
.Pmt(loanInt / 1200, loanTerm * 12, loanAmt)
MsgBox "Monthly payment is " & Format(payment, "Currency")
Shapes, or drawing objects, are represented by three different objects: the Shapes collection, the ShapeRange collection,
and the Shape object. In general, you use the Shapes collection to create shapes and to iterate through all the shapes on
a given worksheet; you use the Shape object to format or modify a single shape; and you use the ShapeRange collection
to modify multiple shapes the same way you work with multiple shapes in the user interface.
Setting Properties for a Shape
Many formatting properties of shapes are not set by properties that apply directly to the Shape or ShapeRange object.
Instead, related shape attributes are grouped under secondary objects, such as the FillFormat object, which contains all
the properties that relate to the shape's fill, or the LinkFormat object, which contains all the properties that are unique to
linked OLE objects. To set properties for a shape, you must first return the object that represents the set of related shape
attributes and then set properties of that returned object. For example, you use the Fill property to return the FillFormat
object, and then you set the ForeColor property of the FillFormat object to set the fill foreground color for the specified
shape, as shown in the following example.
Worksheets(1).Shapes(1).Fill.ForeColor.RGB = RGB(255, 0, 0)
In Visual Basic, there are two ways to apply properties and methods to a set of shapes. These two ways allow you to
perform any operation that you can perform on a single shape on a range of shapes, whether or not you can perform the
same operation in the user interface.
If the operation works on multiple selected shapes in the user interface, you can perform the same operation in
Visual Basic by constructing a ShapeRange collection that contains the shapes you want to work with, and
applying the appropriate properties and methods directly to the ShapeRange collection.
If the operation does not work on multiple selected shapes in the user interface, you can still perform the
operation in Visual Basic by looping through the Shapes collection or through a ShapeRange collection that
contains the shapes you want to work with, and applying the appropriate properties and methods to the
individual Shape objects in the collection.
Many properties and methods that apply to the Shape object and ShapeRange collection fail if applied to certain kinds of
shapes. For example, the TextFrame property fails if applied to a shape that cannot contain text. If you are not positive
that each of the shapes in a ShapeRange collection can have a certain property or method applied to it, do not apply the
property or method to the ShapeRange collection. If you want to apply one of these properties or methods to a collection
of shapes, you must loop through the collection and test each individual shape to make sure it is an appropriate type of
shape before applying the property or method to it.
Worksheets(1).Shapes.Select
Set sr = Selection.ShapeRange
In Microsoft Excel, the Index argument is not optional for the Range property of the Shapes collection, so you cannot use
this property without an argument to create a ShapeRange object containing all shapes in a Shapes collection.
The following are general guidelines for how properties and methods behave when they are applied to a ShapeRange
collection.
Applying a method to the collection is equivalent to applying the method to each individual Shape object in that
collection.
Setting the value of a property of the collection is equivalent to setting the value of the property of each individual
shape in that range.
A property of the collection that returns a constant returns the value of the property for an individual shape in the
collection if all shapes in the collection have the same value for that property. If not all shapes in the collection
have the same value for the property, it returns the "mixed" constant.
A property of the collection that returns a simple data type (such as Long, Single, or String) returns the value of
the property for an individual shape if all shapes in the collection have the same value for that property.
The value of some properties can be returned or set only if there is exactly one shape in the collection. If the
collection contains more than one shape, a run-time error occurs. This is generally the case for returning or
setting properties when the equivalent action in the user interface is possible only with a single shape (actions
such as editing text in a shape or editing the points of a freeform).
The preceding guidelines also apply when you are setting properties of shapes that are grouped under secondary objects of
the ShapeRange collection, such as the FillFormat object. If the secondary object represents operations that can be
performed on multiple selected objects in the user interface, you will be able to return the object from a ShapeRange
collection and set its properties. For example, you can use the Fill property to return the FillFormat object that represents
the fills of all the shapes in the ShapeRange collection. Setting the properties of this FillFormat object will set the same
properties for all the individual shapes in the ShapeRange collection.
The following example constructs a ShapeRange collection that contains all the currently selected shapes in the active
window and sets the foreground color for each selected shape.
The following list represents all of the worksheet functions that can be called using the WorkSheetFunction object. For
more information on a particular function, see the Function Reference topic on Microsoft Office Online.
AccrInt
AccrIntM
Acos
Acosh
AmorDegrc
AmorLinc
And
Application
Asc
Asin
Asinh
Atan2
Atanh
AveDev
Average
AverageIf
AverageIfs
BahtText
BesselI
BesselJ
BesselK
BesselY
BetaDist
BetaInv
Bin2Dec
Bin2Hex
Bin2Oct
BinomDist
Ceiling
ChiDist
ChiInv
ChiTest
Choose
Clean
Combin
Complex
Confidence
Convert
Correl
Cosh
Count
CountA
CountBlank
CountIf
CountIfs
CoupDayBs
CoupDays
CoupDaysNc
CoupNcd
CoupNum
CoupPcd
Covar
Creator
CritBinom
CumIPmt
CumPrinc
DAverage
Days360
Db
Dbcs
DCount
DCountA
Ddb
Dec2Bin
Dec2Hex
Dec2Oct
Degrees
Delta
DevSq
DGet
Disc
DMax
DMin
Dollar
DollarDe
DollarFr
DProduct
DStDev
DStDevP
DSum
Duration
DVar
DVarP
EDate
Effect
EoMonth
Erf
ErfC
Even
ExponDist
Fact
FactDouble
FDist
Find
FindB
FInv
Fisher
FisherInv
Fixed
Floor
Forecast
Frequency
FTest
Fv
FVSchedule
GammaDist
GammaInv
GammaLn
Gcd
GeoMean
GeStep
Growth
HarMean
Hex2Bin
Hex2Dec
Hex2Oct
HLookup
HypGeomDist
IfError
ImAbs
Imaginary
ImArgument
ImConjugate
ImCos
ImDiv
ImExp
ImLn
ImLog10
ImLog2
ImPower
ImProduct
ImReal
ImSin
ImSqrt
ImSub
ImSum
Index
Intercept
IntRate
Ipmt
Irr
IsErr
IsError
IsEven
IsLogical
IsNA
IsNonText
IsNumber
IsOdd
Ispmt
IsText
Kurt
Large
Lcm
LinEst
Ln
Log
Log10
LogEst
LogInv
LogNormDist
Lookup
Match
Max
MDeterm
MDuration
Median
Min
MInverse
MIrr
MMult
Mode
MRound
MultiNomial
NegBinomDist
NetworkDays
Nominal
NormDist
NormInv
NormSDist
NormSInv
NPer
Npv
Oct2Bin
Oct2Dec
Oct2Hex
Odd
OddFPrice
OddFYield
OddLPrice
OddLYield
Or
Parent
Pearson
Percentile
PercentRank
Permut
Phonetic
Pi
Pmt
Poisson
Power
Ppmt
Price
PriceDisc
PriceMat
Prob
Product
Proper
Pv
Quartile
Quotient
Radians
RandBetween
Rank
Rate
Received
Replace
ReplaceB
Rept
Roman
Round
RoundDown
RoundUp
RSq
RTD
Search
SearchB
SeriesSum
Sinh
Skew
Sln
Slope
Small
SqrtPi
Standardize
StDev
StDevP
StEyx
Substitute
Subtotal
Sum
SumIf
SumIfs
SumProduct
SumSq
SumX2MY2
SumX2PY2
SumXMY2
Syd
Tanh
TBillEq
TBillPrice
TBillYield
TDist
Text
TInv
Transpose
Trend
Trim
TrimMean
TTest
USDollar
Var
VarP
Vdb
VLookup
Weekday
WeekNum
Weibull
WorkDay
Xirr
Xnpv
YearFrac
YieldDisc
YieldMat
ZTest
Events are enabled for chart sheets by default. Before you can use events with a Chart object that represents an
embedded chart, you must create a new class module and declare an object of type Chart with events. For example,
assume that a new class module is created and named EventClassModule. The new class module contains the following
code.
After the new object has been declared with events, it appears in the Object drop-down list box in the class module, and
you can write event procedures for this object. (When you select the new object in the Object box, the valid events for that
object are listed in the Procedure drop-down list box.)
Before your procedures will run, however, you must connect the declared object in the class module with the embedded
chart. You can do this by using the following code from any module.
Sub InitializeChart()
Set myClassModule.myChartClass = _
Charts(1).ChartObjects(1).Chart
End Sub
After you run the InitializeChart procedure, the myChartClass object in the class module points to embedded chart 1
on worksheet 1, and the event procedures in the class module will run when the events occur.
Before you can use events with the Application object, you must create a class module and declare an object of type
Application with events. For example, assume that a new class module is created and called EventClassModule. The new
class module contains the following code:
After the new object has been declared with events, it appears in the Object drop-down list box in the class module, and
you can write event procedures for the new object. (When you select the new object in the Object box, the valid events for
that object are listed in the Procedure drop-down list box.)
Before the procedures will run, however, you must connect the declared object in the class module with the Application
object. You can do this with the following code from any module.
Example
Sub InitializeApp()
Set X.App = Application
End Sub
After you run the InitializeApp procedure, the App object in the class module points to the Microsoft Excel Application
object, and the event procedures in the class module will run when the events occur.
Before you can use events with the QueryTable object, you must first create a class module and declare a QueryTable
object with events. For example, assume that you have created a class module and named it ClsModQT. This module
contains the following code:
After you have declared the new object by using events, it appears in the Object drop-down list box in the class module.
Before the procedures will run, however, you must connect the declared object in the class module to the specified
QueryTable object. You can do this by entering the following code in the class module:
After you run this initialization procedure, the object you declared in the class module points to the specified QueryTable
object. You can initialize the event in a module by calling the event. In this example, the first query table on the active
worksheet is connected to the qtQueryTable object.
Sub RunInitQTEvent
clsQueryTable.InitQueryEvent _
QT:=ActiveSheet.QueryTables(1)
End Sub
You can write other event procedures in the object's class. When you click the new object in the Object box, the valid
events for that object are displayed in the Procedure drop-down list box.
If you want to run code in one Microsoft Office application that works with the objects in another application, follow these
steps.
1. Set a reference to the other application's type library in the References dialog box (Tools menu). After you have
done this, the objects, properties, and methods will show up in the Object Browser and the syntax will be
checked at compile time. You can also get context-sensitive Help on them.
2. Declare object variables that will refer to the objects in the other application as specific types. Make sure you
qualify each type with the name of the application that is supplying the object. For example, the following
statement declares a variable that points to a Microsoft Word document and another that refers to a Microsoft
Excel workbook:
Note
You must follow the preceding steps if you want your code to be early bound.
3. Use the CreateObject function with the OLE Programmatic Identifiers of the object you want to work with in the
other application, as shown in the following example. If you want to see the session of the other application, set
the Visible property to True.
4. Apply properties and methods to the object contained in the variable. For example, the following instruction
creates a new Word document.
5. When you are done working with the other application, use the Quit method to close it, as shown in the following
example.
appWd.Quit
AboveAverage Object
Represents an above average visual of a conditional formatting rule. Applying a color or fill to a range or selection to help
you see the value of a cells relative to other cells.
Version Information
Version Added: Excel 2007
Remarks
All conditional formatting objects are contained within a FormatConditions collection object, which is a child of a Range
collection. You can create an above average formatting rule by using either the Add or AddAboveAverage method of the
FormatConditions collection.
Example
The following example builds a dynamic data set and applies color to the above average values through conditional
formatting rules.
Sub AboveAverageCF()
' Applying Conditional Formatting to items above the average. Should appear green
fill and dark green font.
Selection.FormatConditions.AddAboveAverage
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
Selection.FormatConditions(1).AboveBelow = xlAboveAverage
With Selection.FormatConditions(1).Font
.Color = -16752384
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13561798
.TintAndShade = 0
End With
MsgBox "Added an Above Average Conditional Format to Kelli's data. Press F9 to update
values.", vbInformation
End Sub
Methods
Name Description
ModifyAppliesToRange Sets the cell range to which this formatting rule applies.
Sets the priority value for this conditional formatting rule to "1" so that it will be evaluated before all
SetFirstPriority
other rules on the worksheet.
Sets the evaluation order for this conditional formatting rule so it is evaluated after all other rules on
SetLastPriority
the worksheet.
Properties
Name Description
Returns or sets one of the constants of the XlAboveBelow enumeration specifying if the conditional
AboveBelow
formatting rule looks for cell values above or below the range average.
When used without an object qualifier, this property returns an Application object that represents the
Application Microsoft Office Excel application. When used with an object qualifier, this property returns an
Application object that represents the creator of the specified object. Read-only.
AppliesTo Returns a Range object specifying the cell range to which the formatting rule is applied.
Borders Returns a Borders collection that specifies the formatting of cell borders if the conditional formatting
rule evaluates to True. Read-only.
Returns or sets one of the constants of XlCalcFor enumeration which specifies the scope of data to be
CalcFor
evaluated for the conditional format in a PivotTable report.
Returns a Font object that specifies the font formatting if the conditional formatting rule evaluates to
Font
True. Read-only.
Returns or sets a Boolean value specifying if the entire Excel table row should be formatted if the
FormatRow
conditional format rule evaluates to True. The default value is False.
Returns an Interior object that specifies a cell's interior attributes for a conditional formatting rule that
Interior
evaluates to True. Read-only.
Returns or sets the number format applied to a cell if the conditional formatting rule evaluates to
NumberFormat
True. Read/write Variant.
Parent Returns the parent object for the specified object. Read-only.
Returns or sets the priority value of the conditional formatting rule. The priority determines the order
Priority
of evaluation when multiple conditional formatting rules exist in a worksheet.
Returns a Boolean value indicating if the conditional format is being applied to a PivotTable chart.
PTCondition
Read-only.
Returns or sets one of the constants of the XlPivotConditionScope enumeration, which determines the
ScopeType
scope of the conditional format when it is applied to a PivotTable chart.
Returns or sets a Boolean value that determines if additional formatting rules on the cell should be
StopIfTrue
evaluated if the current rule evaluates to True.
Returns one of the constants of the XlFormatConditionType enumeration, which specifies the type of
Type
conditional format. Read-only.
AboveAverage.AboveBelow Property
Returns or sets one of the constants of the XlAboveBelow enumeration, specifying if the conditional formatting rule looks
for cell values above or below the range average or standard deviation.
Version Information
Version Added: Excel 2007
Syntax
expression.AboveBelow
expression A variable that represents an AboveAverage object.
AboveAverage.Application Property
When used without an object qualifier, this property returns an Application object that represents the Microsoft Office
Excel application. When used with an object qualifier, this property returns an Application object that represents the
creator of the specified object. Read-only.
Version Information
Version Added: Excel 2007
Syntax
expression.Application
expression A variable that represents an AboveAverage object.
Remarks
You can use this property with an OLE Automation object to return the application of that object
AddIn Object
Represents a single add-in, either installed or not installed.
Remarks
The AddIn object is a member of the AddIns collection. The AddIns collection contains a list of all the add-ins available
to Microsoft Excel, regardless of whether they’re installed. This list corresponds to the list of add-ins displayed in the Add-
Ins dialog box.
Example
Use AddIns(index), where index is the add-in title or index number, to return a single AddIn object. The following
example installs the Analysis Toolpak add-in.
Don’t confuse the add-in title, which appears in the Add-Ins dialog box, with the add-in name, which is the file name of the
add-in. You must spell the add-in title exactly as it’s spelled in the Add-Ins dialog box, but the capitalization doesn’t have
to match.
The index number represents the position of the add-in in the Add-ins available box in the Add-Ins dialog box. The
following example creates a list that contains specified properties of the available add-ins.
With Worksheets("sheet1")
.Rows(1).Font.Bold = True
.Range("a1:d1").Value = _
Array("Name", "Full Name", "Title", "Installed")
For i = 1 To AddIns.Count
.Cells(i + 1, 1) = AddIns(i).Name
.Cells(i + 1, 2) = AddIns(i).FullName
.Cells(i + 1, 3) = AddIns(i).Title
.Cells(i + 1, 4) = AddIns(i).Installed
Next
.Range("a1").CurrentRegion.Columns.AutoFit
End With
The Add method adds an add-in to the list of available add-ins but doesn’t install the add-in. Set the Installed property of
the add-in to True to install the add-in. To install an add-in that doesn’t appear in the list of available add-ins, you must
first use the Add method and then set the Installed property. This can be done in a single step, as shown in the following
example (note that you use the name of the add-in, not its title, with the Add method).
AddIns.Add("generic.xll").Installed = True
Use Workbooks(index) where index is the add-in filename (not title) to return a reference to the workbook corresponding
to a loaded add-in. You must use the file name because loaded add-ins don’t normally appear in the Workbooks collection.
This example sets the wb variable to the workbook for Myaddin.xla.
Set wb = Workbooks("myaddin.xla")
The following example sets the wb variable to the workbook for the Analysis Toolpak add-in.
Visual Basic for Applications
If the Installed property returns True, but calls to functions in the add-in still fail, the add-in may not actually be loaded.
This is because the Addin object represents the existence and installed state of the add-in but doesn't represent the actual
contents of the add-in workbook.To guarantee that an installed add-in is loaded, you should open the add-in workbook. The
following example opens the workbook for the add-in named "My Addin" if the add-in isn’t already present in the
Workbooks collection.
AddIn.Application Property
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.
Syntax
expression.Application
expression A variable that represents an AddIn object.
Example
This example displays a message about the application that created myObject.
AddIn.CLSID Property
Returns a read-only unique identifier, or CLSID, identifying an object, as a String.
Syntax
expression.CLSID
expression A variable that represents an AddIn object.
Example
This example returns the CLSID of an add-in titled "Analysis ToolPak". This example assumes the "Analysis ToolPak" has
been installed.
Sub FindCLSID()
End Sub
AddIn.Creator Property
Returns a 32-bit integer that indicates the application in which this object was created. Read-only Long.
Syntax
expression.Creator
expression An expression that returns a AddIn object.
Return Value
XlCreator
Remarks
If the object was created in Microsoft Excel, this property returns the string XCEL, which is equivalent to the hexadecimal
number 5843454C. The Creator property is designed to be used in Microsoft Excel for the Macintosh, where each
application has a four-character creator code. For example, Microsoft Excel has the creator code XCEL.
AddIn.FullName Property
Returns the name of the object, including its path on disk, as a string. Read-only String.
Syntax
expression.FullName
expression A variable that represents an AddIn object.
Example
This example displays the path and file name of every available add-in.
AddIn.Installed Property
True if the add-in is installed. Read/write Boolean.
Syntax
expression.Installed
expression A variable that represents an AddIn object.
Remarks
Setting this property to True installs the add-in and calls its Auto_Add functions. Setting this property to False removes the
add-in and calls its Auto_Remove functions.
Example
This example uses a message box to display the installation status of the Solver add-in.
AddIn.Name Property
Returns a String value that represents the name of the object.
Syntax
expression.Name
expression A variable that represents an AddIn object.
AddIn.Parent Property
Returns the parent object for the specified object. Read-only.
Syntax
expression.Parent
expression A variable that represents an AddIn object.
AddIn.Path Property
Returns a String value that represents the complete path to the application, excluding the final separator and name of the
application.
Syntax
expression.Path
expression A variable that represents an AddIn object.
AddIn.progID Property
Returns the programmatic identifiers for the object. Read-only String.
Syntax
expression.progID
expression A variable that represents an AddIn object.
Example
This example creates a list of the programmatic identifiers for the OLE objects on worksheet one.
rw = 0
For Each o in Worksheets(1).OLEObjects
With Worksheets(2)
rw = rw + 1
.cells(rw, 1).Value = o.ProgId
End With
Next
AddIns Collection
A collection of AddIn objects that represents all the add-ins available to Microsoft Excel, regardless of whether they’re
installed.
Remarks
This list corresponds to the list of add-ins displayed in the Add-Ins dialog box.
Example
Use the AddIns property to return the AddIns collection. The following example creates a list that contains the names and
installed states of all the available add-ins.
Sub DisplayAddIns()
Worksheets("Sheet1").Activate
rw = 1
For Each ad In Application.AddIns
Worksheets("Sheet1").Cells(rw, 1) = ad.Name
Worksheets("Sheet1").Cells(rw, 2) = ad.Installed
rw = rw + 1
Next
End Sub
Use the Add method to add an add-in to the list of available add-ins. The Add method adds an add-in to the list but doesn’t
install the add-in. Set the Installed property of the add-in to True to install the add-in. To install an add-in that doesn’t
appear in the list of available add-ins, you must first use the Add method and then set the Installed property. This can be
done in a single step, as shown in the following example (note that you use the name of the add-in, not its title, with the
Add method).
AddIns.Add("generic.xll").Installed = True
Use AddIns(index) where index is the add-in title or index number to return a single AddIn object. The following example
installs the Analysis Toolpak add-in.
Don’t confuse the add-in title, which appears in the Add-Ins dialog box, with the add-in name, which is the file name of the
add-in. You must spell the add-in title exactly as it’s spelled in the Add-Ins dialog box, but the capitalization doesn’t have
to match.
AddIns.Application Property
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.
Syntax
expression.Application
expression A variable that represents an AddIns object.
Example
This example displays a message about the application that created myObject.
AddIns.Item Property
Returns a single object from a collection.
Syntax
expression.Item(Index)
expression A variable that represents an AddIns object.
Parameters
Data
Name Required/Optional Description
Type
Example
This example displays the status of the Analysis ToolPak add-in. Note that the string used as the index to the AddIns
method is the Title property of the AddIn object.
AddIns.Add Method
Adds a new add-in file to the list of add-ins. Returns an AddIn object.
Syntax
expression.Add(FileName, CopyFile)
expression A variable that represents an AddIns object.
Parameters
Data
Name Required/Optional Description
Type
The name of the file that contains the add-in you want to add to the list in the add-in
Filename Required String
manager.
Ignored if the add-in file is on a hard disk. True to copy the add-in to your hard disk, if
the add-in is on a removable medium (a floppy disk or compact disc). False to have the
CopyFile Optional Variant
add-in remain on the removable medium. If this argument is omitted, Microsoft Excel
displays a dialog box and asks you to choose.
Return Value
An AddIn object that represents the new add-in.
Remarks
This method does not install the new add-in. You must set the Installed property to install the add-in.
Example
This example inserts the add-in Myaddin.xla from drive A. When you run this example, Microsoft Excel copies the file
A:\Myaddin.xla to the Library folder on your hard disk and adds the add-in title to the list in the Add-Ins dialog box.
Sub UseAddIn()
End Sub
Adjustments Object
Contains a collection of adjustment values for the specified AutoShape, WordArt object, or connector.
Remarks
Each adjustment value represents one way an adjustment handle can be adjusted. Because some adjustment handles can
be adjusted in two ways — for instance, some handles can be adjusted both horizontally and vertically — a shape can have
more adjustment values than it has adjustment handles. A shape can have up to eight adjustments.
Use the Adjustments property to return an Adjustments object. Use Adjustments(index), where index is the
adjustment value’s index number, to return a single adjustment value.
Different shapes have different numbers of adjustment values, different kinds of adjustments change the geometry of a
shape in different ways, and different kinds of adjustments have different ranges of valid values. For example, the following
illustration shows what each of the four adjustment values for a right-arrow callout contributes to the definition of the
callout’s geometry.
Note
Because each adjustable shape has a different set of adjustments, the best way to verify the adjustment behavior for a specific shape is to
manually create an instance of the shape, make adjustments with the macro recorder turned on, and then examine the recorded code.
The following table summarizes the ranges of valid adjustment values for different types of adjustments. In most cases, if
you specify a value that’s beyond the range of valid values, the closest valid value will be assigned to the adjustment.
Type of
Valid values
adjustment
Generally the value 0.0 represents the left or top edge of the shape and the value 1.0 represents the right or bottom
edge of the shape. Valid values correspond to valid adjustments you can make to the shape manually. For example, if
Linear
you can only pull an adjustment handle half way across the shape manually, the maximum value for the corresponding
(horizontal or
adjustment will be 0.5. For shapes such as connectors and callouts, where the values 0.0 and 1.0 represent the limits of
vertical)
the rectangle defined by the starting and ending points of the connector or callout line, negative numbers and numbers
greater than 1.0 are valid values.
An adjustment value of 1.0 corresponds to the width of the shape. The maximum value is 0.5, or half way across the
Radial
shape.
Values are expressed in degrees. If you specify a value outside the range – 180 to 180, it will be normalized to be
Angle
within that range.
Example
The following example adds a right-arrow callout to myDocument and sets adjustment values for the callout. Note that
although the shape has only three adjustment handles, it has four adjustments. Adjustments three and four both
correspond to the handle between the head and neck of the arrow.
Adjustments.Application Property
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.
Syntax
expression.Application
expression A variable that represents an Adjustments object.
Example
This example displays a message about the application that created myObject.
AllowEditRange Object
Represents the cells that can be edited on a protected worksheet.
Remarks
Use the Add method or the Item property of the AllowEditRanges collection to return an AllowEditRange object.
Once an AllowEditRange object has been returned, you can use the ChangePassword method to change the password
to access a range that can be edited on a protected worksheet.
Example
In this example, Microsoft Excel allows edits to range "A1:A4" on the active worksheet, notifies the user, then changes the
password for this specified range and notifies the user of this change.
Sub UseChangePassword()
wksOne.Protection.AllowEditRanges(1).ChangePassword _
Password:=wksPassword
End Sub
AllowEditRange.Users Property
Returns a UserAccessList object for the protected range on a worksheet.
Syntax
expression.Users
expression A variable that represents an AllowEditRange object.
Example
In this example, Microsoft Excel displays the name of the first user allowed access to the first protected range on the active
worksheet. This example assumes that a range has been chosen to be protected and that a particular user has been given
access to this range.
Sub DisplayUserName()
End Sub
AllowEditRange.ChangePassword Method
Changes the password for a range that can be edited on a protected worksheet.
Syntax
expression.ChangePassword(Password)
expression A variable that represents an AllowEditRange object.
Parameters
Data
Name Required/Optional Description
Type
Example
In this example, Microsoft Excel allows edits to range "A1:A4" on the active worksheet, notifies the user, changes the
password for this specified range, and notifies the user of the change. The worksheet must be unprotected before running
this code.
Sub UseChangePassword()
End Sub
AllowEditRanges Collection
A collection of all the AllowEditRange objects that represent the cells that can be edited on a protected worksheet.
Remarks
Use the AllowEditRanges property of the Protection object to return an AllowEditRanges collection.
Once an AllowEditRanges collection has been returned, you can use the Add method to add a range that can be edited
on a protected worksheet.
Example
In this example, Microsoft Excel allows edits to range "A1:A4" on the active worksheet and notifies the user of the title and
address of the specified range.
Sub UseAllowEditRanges()
End Sub
AllowEditRanges.Item Property
Returns a single object from a collection.
Syntax
expression.Item(Index)
expression A variable that represents an AllowEditRanges object.
Parameters
Data
Name Required/Optional Description
Type
Example
This example allows edits to range ("A1:A4") on the active worksheet, notifies the user, then changes the password for this
specified range and notifies the user of this change.
Sub UseChangePassword()
End Sub
Application Object
Represents the entire Microsoft Excel application.
Remarks
The Application object contains:
Example
Use the Application property to return the Application object. The following example applies the Windows property to
the Application object.
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 user-interface objects, such as the active cell
(ActiveCell property), can be used without the Application object qualifier. For example, instead of writing
Application.ActiveCell.Font.Bold = True
ActiveCell.Font.Bold = True
Application.ActiveCell Property
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.
Syntax
expression.ActiveCell
expression A variable that represents an Application object.
Remarks
If you don't specify an object qualifier, this property returns the active cell in the active window.
Be careful to distinguish between the active cell and the selection. The active cell is a single cell inside the current selection.
The selection may contain more than one cell, but only one is the active cell.
The following expressions all return the active cell, and are all equivalent.
ActiveCell
Application.ActiveCell
ActiveWindow.ActiveCell
Application.ActiveWindow.ActiveCell
Example
This example uses a message box to display the value in the active cell. Because the ActiveCell property fails if the active
sheet isn't a worksheet, the example activates Sheet1 before using the ActiveCell property.
Worksheets("Sheet1").Activate
MsgBox ActiveCell.Value
This example changes the font formatting for the active cell.
Worksheets("Sheet1").Activate
With ActiveCell.Font
.Bold = True
.Italic = True
End With
Application.ActiveChart Property
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.
Syntax
expression.ActiveChart
expression A variable that represents an Application object.
Remarks
If you don't specify an object qualifier, this property returns the active chart in the active workbook.
Example
This example turns on the legend for the active chart.
ActiveChart.HasLegend = True
Application.ActivePrinter Property
Returns or sets the name of the active printer. Read/write String.
Syntax
expression.ActivePrinter
expression A variable that represents an Application object.
Example
This example displays the name of the active printer.
Application.ActiveSheet Property
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.
Syntax
expression.ActiveSheet
expression A variable that represents an Application object.
Remarks
If you don’t specify an object qualifier, this property returns the active sheet in the active workbook.
If a workbook appears in more than one window, the ActiveSheet property may be different in different windows.
Example
This example displays the name of the active sheet.
Application.ActiveWindow Property
Returns a Window object that represents the active window (the window on top). Read-only. Returns Nothing if there are
no windows open.
Syntax
expression.ActiveWindow
expression A variable that represents an Application object.
Example
This example displays the name (Caption property) of the active window.
Application.ActiveWorkbook Property
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.
Syntax
expression.ActiveWorkbook
expression A variable that represents an Application object.
Example
This example displays the name of the active workbook.
Application.AddIns Property
Returns an AddIns collection that represents all the add-ins listed in the Add-Ins dialog box (Tools menu). Read-only.
Syntax
expression.AddIns
expression A variable that represents an Application object.
Remarks
Using this method without an object qualifier is equivalent to Application.Addins.
Example
This example displays the status of the Analysis ToolPak add-in. Note that the string used as the index to the AddIns
collection is the title of the add-in, not the add-in’s file name.
Application.AltStartupPath Property
Returns or sets the name of the alternate startup folder. Read/write String.
Syntax
expression.AltStartupPath
expression A variable that represents an Application object.
Example
This example sets the alternate startup folder.
Application.AltStartupPath = "C:\EXCEL\MACROS"
Application.Application Property
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.
Syntax
expression.Application
expression A variable that represents an Application object.
Example
This example displays a message about the application that created myObject.
Application.Assistant Property
Returns an Assistant object for Microsoft Excel.
Syntax
expression.Assistant
expression A variable that represents an Application object.
Remarks
Using this property without an object qualifier is equivalent to using Application.Assistant.
Example
This example makes the Office Assistant visible.
Assistant.Visible = True
Application.AutoCorrect Property
Returns an AutoCorrect object that represents the Microsoft Excel AutoCorrect attributes. Read-only.
Syntax
expression.AutoCorrect
expression A variable that represents an Application object.
Example
This example substitutes the word "Temp." for the word "Temperature" in the array of AutoCorrect replacements.
With Application.AutoCorrect
.AddReplacement "Temperature", "Temp."
End With
Application.AutoFormatAsYouTypeReplaceHyperlinks Property
True (default) if Microsoft Excel automatically formats hyperlinks as you type. False if Excel does not automatically format
hyperlinks as you type. Read/write Boolean.
Syntax
expression.AutoFormatAsYouTypeReplaceHyperlinks
expression A variable that represents an Application object.
Example
In this example, Microsoft Excel determines if the ability to format hyperlinks automatically as they are typed is enabled and
notifies the user.
Sub CheckHyperlinks()
End Sub
Application.AutomationSecurity Property
Returns or sets an MsoAutomationSecurity constant that represents the security mode Microsoft Excel uses when
programmatically opening files. Read/write.
Syntax
expression.AutomationSecurity
expression A variable that represents an Application object.
Remarks
This property is automatically set to msoAutomationSecurityLow when the application is started. Therefore, to avoid
breaking solutions that rely on the default setting, you should be careful to reset this property to
msoAutomationSecurityLow after programmatically opening a file. Also, this property should be set immediately before
and after opening a file programmatically to avoid malicious subversion.
msoAutomationSecurityForceDisable. Disables all macros in all files opened programmatically without showing any security alerts.
Note
This setting does not disable Microsoft Excel 4.0 macros. If a file that contains Microsoft Excel 4.0 macros is opened programmatically,
the user will be prompted to decide whether or not to open the file.
msoAutomationSecurityLow. Enables all macros. This is the default value when the application is started.
Setting ScreenUpdating to False does not affect alerts and will not affect security warnings. The DisplayAlerts setting
will not apply to security warnings. For example, if the user sets DisplayAlerts equal to False and AutomationSecurity
to msoAutomationSecurityByUI, while the user is on Medium security level, then there will be security warnings while
the macro is running. This allows the macro to trap file open errors, while still showing the security warning if the file open
succeeds.
Example
This example captures the current automation security setting, changes the setting to disable macros, displays the Open
dialog box, and after opening the selected document, sets the automation security back to its original setting.
Sub Security()
Dim secAutomation As MsoAutomationSecurity
secAutomation = Application.AutomationSecurity
Application.AutomationSecurity = msoAutomationSecurityForceDisable
Application.FileDialog(msoFileDialogOpen).Show
Application.AutomationSecurity = secAutomation
End Sub
Application.AutoPercentEntry Property
True if entries in cells formatted as percentages aren’t automatically multiplied by 100 as soon as they are entered.
Read/write Boolean.
Syntax
expression.AutoPercentEntry
expression A variable that represents an Application object.
Example
This example enables automatic multiplication by 100 for subsequent entries in cells formatted as percentages.
Application.AutoPercentEntry = False
Application.AutoRecover Property
Returns an AutoRecover object, which backs up all file formats on a timed interval.
Syntax
expression.AutoRecover
expression A variable that represents an Application object.
Remarks
Valid time intervals are whole numbers from 1 to 120.
Example
In this example, the Time property is used in conjunction with the AutoRecover property to set the time interval for
Microsoft Excel to wait before saving another copy to five minutes.
Sub UseAutoRecover()
Application.AutoRecover.Time = 5
MsgBox "The time that will elapse between each automatic " & _
"save has been set to " & _
Application.AutoRecover.Time & " minutes."
End Sub
Application.Build Property
Returns the Microsoft Excel build number. Read-only Long.
Syntax
expression.Build
expression A variable that represents an Application object.
Remarks
It’s usually safer to test the Version property, unless you’re sure you need to know the build number.
Example
This example tests the Build property.
Application.CalculateBeforeSave Property
True if workbooks are calculated before they're saved to disk (if the Calculation property is set to xlManual). This
property is preserved even if you change the Calculation property. Read/write Boolean.
Syntax
expression.CalculateBeforeSave
expression A variable that represents an Application object.
Example
This example sets Microsoft Excel to calculate workbooks before they're saved to disk.
Application.Calculation = xlManual
Application.CalculateBeforeSave = True
Application.CalculationInterruptKey Property
Sets or returns an XlCalculationInterruptKey constant that specifies the key that can interrupt Microsoft Excel when
performing calculations. Read/write.
Syntax
expression.CalculationInterruptKey
expression A variable that represents an Application object.
Example
In this example, Microsoft Excel determines the setting for the calculation interrupt key and notifies the user.
Sub CheckInterruptKey()
' Determine the calculation interrupt key and notify the user.
Select Case Application.CalculationInterruptKey
Case xlAnyKey
MsgBox "The calcuation interrupt key is set to any key."
Case xlEscKey
MsgBox "The calcuation interrupt key is set to 'Escape'"
Case xlNoKey
MsgBox "The calcuation interrupt key is set to no key."
End Select
End Sub
Application.CalculationState Property
Returns an XlCalculationState constant that indicates the calculation state of the application, for any calculations that are
being performed in Microsoft Excel. Read-only.
Syntax
expression.CalculationState
expression A variable that represents an Application object.
Example
In this example, Microsoft Excel checks to see if any calculations are being performed. If no calculations are being
performed, a message displays the calculation state as "Done". Otherwise, a message displays the calculation state as "Not
Done".
Sub StillCalculating()
End Sub
Application.CalculationVersion Property
Returns a number whose rightmost four digits are the minor calculation engine version number, and whose other digits (on
the left) are the major version of Microsoft Excel. Read-only Long.
Syntax
expression.CalculationVersion
expression A variable that represents an Application object.
Remarks
If the workbook was saved in an earlier version of Excel and if the workbook hasn't been fully recalculated, then this
property returns 0.
Example
This example compares the version of Microsoft Excel with the version of Excel that the workbook was last calculated in. If
the two version numbers are different, the example sets the blnFullCalc variable to True.
If Application.CalculationVersion <> _
Workbooks(1).CalculationVersion Then
blnFullCalc = True
Else
blnFullCalc = False
End If
Application.Caller Property
Returns information about how Visual Basic was called (for more information, see the Remarks section).
Syntax
expression.Caller(Index)
expression A variable that represents an Application object.
Parameters
Data
Name Required/Optional Description
Type
An index to the array. This argument is used only when the property returns an array (for
Index Optional Variant
more information, see the Remarks section).
Remarks
This property returns information about how Visual Basic was called, as shown in the following table.
A custom function entered in a single cell A Range object specifying that cell
A macro set by either the OnDoubleClick or OnEntry The name of the chart object identifier or cell reference (if applicable) to
property which the macro applies
The Macro dialog box (Tools menu), or any caller not
The #REF! error value
described above
Example
This example displays information about how Visual Basic was called.
Syntax
expression.CellDragAndDrop
expression A variable that represents an Application object.
Example
This example enables dragging and dropping cells.
Application.CellDragAndDrop = True
Application.Charts Property
Returns a Sheets collection that represents all the chart sheets in the active workbook.
Syntax
expression.Charts
expression A variable that represents an Application object.
Example
This example sets the text for the title of Chart1.
With Charts("Chart1")
.HasTitle = True
.ChartTitle.Text = "First Quarter Sales"
End With
Application.ClipboardFormats Property
Returns the formats that are currently on the Clipboard, as an array of numeric values. To determine whether a particular
format is on the Clipboard, compare each element in the array with the appropriate constant listed in the Remarks section.
Read-only Variant.
Syntax
expression.ClipboardFormats(Index)
expression A variable that represents an Application object.
Parameters
Data
Name Required/Optional Description
Type
The array element to be returned. If this argument is omitted, the property returns the
Index Optional Variant
entire array of formats that are currently on the Clipboard. For more information, see the
Remarks section.
Remarks
This property returns an array of numeric values. To determine whether a particular format is on the Clipboard compare
each element of the array with one of the XlClipboardFormat constants.
Example
This example displays a message box if the Clipboard contains a rich-text format (RTF) object. You can create an RTF object
by copying text from a Word document.
aFmts = Application.ClipboardFormats
For Each fmt In aFmts
If fmt = xlClipboardFormatRTF Then
MsgBox "Clipboard contains rich text"
End If
Next
Application.COMAddIns Property
Returns the COMAddIns collection for Microsoft Excel, which represents the currently installed COM add-ins. Read-only.
Syntax
expression.COMAddIns
expression A variable that represents an Application object.
Example
This example displays the number of COM add-ins that are currently installed.
Application.CommandBars Property
Returns a CommandBars object that represents the Microsoft Excel command bars. Read-only.
Syntax
expression.CommandBars
expression An expression that returns a Application object.
Remarks
Used with the Application object, this property returns the set of built-in and custom command bars available to the
application.
When a workbook is embedded in another application and activated by the user by double-clicking the workbook, using this
property with a Workbook object returns the set of Microsoft Excel command bars available within the other application. At
all other times, using this property with a Workbook object returns Nothing.
There is no programmatic way to return the set of command bars attached to a workbook.
Example
This example deletes all custom command bars that aren’t visible.
Visual Basic for Applications
Application.Worksheets Property
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.
This example adds a new worksheet to the active workbook and then sets the name of the worksheet.
Application.Wait Method
Pauses a running macro until a specified time. Returns True if the specified time has arrived.
Syntax
expression.Wait(Time)
expression A variable that represents an Application object.
Parameters
Time Required Variant The time at which you want the macro to resume, in Microsoft Excel date format.
Return Value
Boolean
Remarks
The Wait method suspends all Microsoft Excel activity and may prevent you from performing other operations on your
computer while Wait is in effect. However, background processes such as printing and recalculation continue.
Example
This example pauses a running macro until 6:23 P.M. today.
Application.Wait "18:23:00"
newHour = Hour(Now())
newMinute = Minute(Now())
newSecond = Second(Now()) + 10
waitTime = TimeSerial(newHour, newMinute, newSecond)
Application.Wait waitTime
CalculatedMember Object
Represents the calculated fields and calculated items for PivotTables with Online Analytical Processing (OLAP) (OLAP: A
database technology that has been optimized for querying and reporting, instead of processing transactions. OLAP data is
organized hierarchically and stored in cubes instead of tables.) data sources.
Remarks
Use the Add method or the Item property of the CalculatedMembers collection to return a CalculatedMember object.
With a CalculatedMember object you can check the validity of a calculated field or item in a PivotTable using the IsValid
property.
Note
The IsValid property will return True if the PivotTable is not currently connected to the data source. Use the MakeConnection method
before testing the IsValid property.
Example
The following example notifies the user if the calculated member is valid or not. This example assumes a PivotTable exists
on the active worksheet that contains either a valid or invalid calculated member.
Visual Basic for Applications
Sub CheckValidity()
' Handle run-time error if external source is not an OLEDB data source.
On Error GoTo Not_OLEDB
End Sub
CalculatedMembers Collection
Remarks
Each CalculatedMember object represents a calculated member or calculated measure.
Use the CalculatedMembers property of the PivotTable object to return a CalculatedMembers collection.
Example
The following example adds a set to a PivotTable, assuming a PivotTable exists on the active worksheet.
Sub UseCalculatedMember()
pvtTable.CalculatedMembers.Add Name:="[Beef]", _
Formula:="'{[Product].[All Products].Children}'", _
Type:=xlCalculatedSet
End Sub
ChartArea Object
Represents the chart area of a chart.
Remarks
The chart area includes everything, including the plot area. However, the plot area has its own fill, so filling the plot area
does not fill the chart area.
For information about formatting the plot area, see PlotArea Object.
Example
The following example turns off the border for the chart area in embedded chart 1 on the worksheet named "Sheet1."
Worksheets("Sheet1").ChartObjects(1).Chart. _
ChartArea.Format.Line.Visible = False
ChartFillFormat Object
Used only with charts. Represents fill formatting for chart elements.
Remarks
Use the Fill property to return a ChartFillFormat object.
Example
The following example sets the foreground color, background color, and gradient for the chart area fill on Chart 1.
With Charts(1).ChartArea.Fill
.Visible = True
.ForeColor.SchemeColor = 15
.BackColor.SchemeColor = 17
.TwoColorGradient Style:=msoGradientHorizontal, Variant:=1
End With
ChartGroup Object
Represents one or more series plotted in a chart with the same format.
Remarks
A chart contains one or more chart groups, each chart group contains one or more Series objects, and each series contains
one or more Points objects. For example, a single chart might contain both a line chart group, containing all the series
plotted with the line chart format, and a bar chart group, containing all the series plotted with the bar chart format. The
ChartGroup object is a member of the ChartGroups collection.
Use ChartGroups(index), where index is the chart-group index number, to return a single ChartGroup object.
Because the index number for a particular chart group can change if the chart format used for that group is changed, it may
be easier to use one of the named chart group shortcut methods to return a particular chart group. The PieGroups method
returns the collection of pie chart groups in a chart, the LineGroups method returns the collection of line chart groups, and
so on. Each of these methods can be used with an index number to return a single ChartGroup object, or without an index
number to return a ChartGroups collection.
Example
The following example adds drop lines to chart group 1 on chart sheet 1.
Charts(1).ChartGroups(1).HasDropLines = True
If the chart has been activated, you can use the ActiveChart property.
Charts(1).Activate
ActiveChart.ChartGroups(1).HasDropLines = True
ChartGroups Object
Represents one or more series plotted in a chart with the same format.
Remarks
A ChartGroups collection is a collection of all the ChartGroup objects in the specified chart. A chart contains one or more
chart groups, each chart group contains one or more series, and each series contains one or more points. For example, a
single chart might contain both a line chart group, containing all the series plotted with the line chart format, and a bar
chart group, containing all the series plotted with the bar chart format.
Use the ChartGroups method to return the ChartGroups collection. The following example displays the number of chart
groups on embedded chart 1 on worksheet 1.
MsgBox Worksheets(1).ChartObjects(1).Chart.ChartGroups.Count
Use ChartGroups(index), where index is the chart-group index number, to return a single ChartGroup object. The
following example adds drop lines to chart group 1 on chart sheet 1.
Charts(1).ChartGroups(1).HasDropLines = True
Charts(1).Activate
ActiveChart.ChartGroups(1).HasDropLines = True
Because the index number for a particular chart group can change if the chart format used for that group is changed, it may
be easier to use one of the named chart group shortcut methods to return a particular chart group. The PieGroups method
returns the collection of pie chart groups in a chart, the LineGroups method returns the collection of line chart groups, and
so on. Each of these methods can be used with an index number to return a single ChartGroup object, or without an index
number to return a ChartGroups collection.
ChartObject Object
Represents an embedded chart on a worksheet.
Remarks
The ChartObject object acts as a container for a Chart object. Properties and methods for the ChartObject object
control the appearance and size of the embedded chart on the worksheet. The ChartObject object is a member of the
ChartObjects collection. The ChartObjects collection contains all the embedded charts on a single sheet.
Use ChartObjects(index), where index is the embedded chart index number or name, to return a single ChartObject
object.
Example
The following example sets the pattern for the chart area in embedded Chart 1 on the worksheet named "Sheet1."
Worksheets("Sheet1").ChartObjects(1).Chart. _
ChartArea.Format.Fill.Pattern = msoPatternLightDownwardDiagonal
The embedded chart name is shown in the Name box when the embedded chart is selected. Use the Name property to set
or return the name of the ChartObject object. The following example puts rounded corners on the embedded chart named
"Chart 1" on the worksheet named "Sheet1."
Charts Collection
A collection of all the chart sheets in the specified or active workbook.
Remarks
Each chart sheet is represented by a Chart object. This does not include charts embedded on worksheets or dialog sheets.
For information about embedded charts, see the Chart or ChartObject topics.
Example
Use the Charts property to return the Charts collection. The following example prints all chart sheets in the active
workbook.
Charts.PrintOut
Use the Add method to create a new chart sheet and add it to the workbook. The following example adds a new chart
sheet to the active workbook and places the new chart sheet immediately after the worksheet named Sheet1.
Charts.Add After:=Worksheets("Sheet1")
You can combine the Add method with the ChartWizard method to add a new chart that contains data from a worksheet.
The following example adds a new line chart based on data in cells A1:A20 on the worksheet named Sheet1.
With Charts.Add
.ChartWizard source:=Worksheets("Sheet1").Range("A1:A20"), _
Gallery:=xlLine, Title:="February Data"
End With
Use Charts(index), where index is the chart-sheet index number or name, to return a single Chart object. The following
example changes the color of series 1 on chart sheet 1 to red.
Charts(1).SeriesCollection(1).Format.Fill.ForeColor.RGB = rgbRed
The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets). Use Sheets(index),
where index is the sheet name or number, to return a single sheet.
ChartTitle Object
Represents the chart title.
Remarks
Use the ChartTitle property to return the ChartTitle object.
The ChartTitle object doesn’t exist and cannot be used unless the HasTitle property for the chart is True.
Example
The following example adds a title to embedded chart one on the worksheet named "Sheet1."
With Worksheets("sheet1").ChartObjects(1).Chart
.HasTitle = True
.ChartTitle.Text = "February Sales"
End With
ChartView Object
Represents a view of a chart.
Version Information
Version Added: Excel 2007
Remarks
The ChartView object is one of the objects that can be returned by the SheetViews collection, similar to the Sheets
collection. The ChartView object applies only to chart sheets.
Example
The following example returns a ChartView object.
ActiveWindow.SheetViews.Item(1)
ActiveWindow.SheetViews.Item(1).Sheet
ColorFormat Object
Represents the color of a one-color object, the foreground or background color of an object with a gradient or patterned fill,
or the pointer color.
Remarks
You can set colors to an explicit red-green-blue value (by using the RGB property) or to a color in the color scheme (by
using the SchemeColor property).
Use one of the properties listed in the following table to return a ColorFormat object.
Use this property With this object To return a ColorFormat object that represents this
BackColor FillFormat The background fill color (used in a shaded or patterned fill)
ForeColor FillFormat The foreground fill color (or simply the fill color for a solid fill)
BackColor LineFormat The background line color (used in a patterned line)
ForeColor LineFormat The foreground line color (or just the line color for a solid line)
ForeColor ShadowFormat The shadow color
ExtrusionColor ThreeDFormat The color of the sides of an extruded object
Example
Use the RGB property to set a color to an explicit red-green-blue value. The following example adds a rectangle to
myDocument and then sets the foreground color, background color, and gradient for the rectangle's fill.
ColorScale Object
Represents a color scale conditional formatting rule.
Version Information
Version Added: Excel 2007
Remarks
All conditional formatting objects are contained within a FormatConditions collection object, which is a child of a Range
collection. You can create a color scale formatting rule by using either the Add or AddColorScale method of the
FormatConditions collection.
Color scales are visual guides that help you understand data distribution and variation. You can apply either a two-color or a
three-color scale to a range of data, data in a table, or data in a PivotTable report. For a two-color scale conditional format,
you assign the value, type, and color to the minimum and maximum thresholds of a range. A three-color scale also has a
midpoint threshold.
Each of these thresholds is determined by setting the properties of the ColorScaleCriteria object. The
ColorScaleCriteria object, which is a child of the ColorScale object, is a collection of all of the ColorScaleCriterion
objects for the color scale.
Example
The following code example creates a range of numbers and then applies a two-color scale conditional formatting rule to
that range. The color for the minimum threshold is then assigned to red and the maximum threshold to blue.
Sub CreateColorScaleCF()
Dim cfColorScale As ColorScale
Range("C1:C10").Select
'Create a two-color ColorScale object for the created sample data range
Set cfColorScale = Selection.FormatConditions.AddColorScale(ColorScaleType:=2)
End Sub
ColorScaleCriteria Collection
A collection of ColorScaleCriterion objects that represents all of the criteria for a color scale conditional format. Each
criterion specifies the minimum, midpoint, or maximum threshold for the color scale.
Version Information
Version Added: Excel 2007
Remarks
To return the ColorScaleCriteria collection, use the ColorScaleCriteria property of the ColorScale object.
Example
The following code example creates a range of numbers and then applies a two-color scale conditional formatting rule to
that range. The color for the minimum threshold is then assigned to red and the maximum threshold to blue by indexing
into the ColorScaleCriteria collection to set individual criteria.
Sub CreateColorScaleCF()
'Create a two-color ColorScale object for the created sample data range
Set cfColorScale = Selection.FormatConditions.AddColorScale(ColorScaleType:=2)
End Sub
ColorStop Object
Represents the color stop point for a gradient fill in an range or selection.
Version Information
Version Added: Excel 2007
Remarks
The ColorStop collection allows you to set properties for the cell fill including Color, ThemeColor, TintAndShade.
Example
The following example shows how to apply properties to the ColorStop.
With Selection.Interior
.Pattern = xlPatternLinearGradient
.Gradient.Degree = 135
.Gradient.ColorStops.Clear
End With
With Selection.Interior.Gradient.ColorStops.Add(0)
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
With Selection.Interior.Gradient.ColorStops.Add(0.5)
.ThemeColor = xlThemeColorAccent1
.TintAndShade = 0
End With
With Selection.Interior.Gradient.ColorStops.Add(1)
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
End With
Comments Object
A collection of cell comments.
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.
Use the AddComment method to add a comment to a range. The following example adds a comment to cell E5 on
worksheet one.
With Worksheets(1).Range("e5").AddComment
.Visible = False
.Text "reviewed on " & Date
End With
Use Comments(index), where index is the comment number, to return a single comment from the Comments collection.
The following example hides comment two on worksheet one.
Worksheets(1).Comments(2).Visible = False
ConditionValue Object
Represents how the shortest bar or longest bar is evaluated for a data bar conditional formatting rule.
Version Information
Version Added: Excel 2007
Remarks
The ConditionValue object is returned using either the MaxPoint or MinPoint property of the Databar object.
You can change the type of evaluation from the default setting (lowest value for the shortest bar and highest value for the
longest bar) by using the Modify method.
Example
The following example creates a range of data and then applies a data bar to the range. You will notice that because there
is an extremely low and high value in the range, the middle values have data bars that are of similiar length. To
disambiguate the middle values, the sample code uses the ConditionValue object to change how the thresholds are
evaluated to percentiles.
Range("D1:D9").Select
End Sub
Connections Object
A collection of Connection objects for the specified workbook.
Version Information
Version Added: Excel 2007
Example
The following example shows how to add a connection to a workbook from an existing file.
ActiveWorkbook.Connections.AddFromFile _
"C:\Documents and Settings\rodchis\My Documents\My Data Sources\Northwind 2007
Customers.odc"
ConnectorFormat Object
Contains properties and methods that apply to connectors.
Remarks
A connector is a line that attaches two other shapes at points called connection sites. If you rearrange shapes that are
connected, the geometry of the connector will be automatically adjusted so that the shapes remain connected.
Connection sites are generally numbered according to the rules presented in the following table.
AutoShapes, WordArt, pictures, and OLE objects The connection sites are numbered starting at the top and proceeding counterclockwise.
Freeforms The connection sites are the vertices, and they correspond to the vertex numbers.
Use the ConnectorFormat property to return a ConnectorFormat object. Use the BeginConnect and EndConnect
methods to attach the ends of the connector to other shapes in the document. Use the RerouteConnections method to
automatically find the shortest path between the two shapes connected by the connector. Use the Connector property to
see whether a shape is a connector.
Note
You assign a size and a position when you add a connector to the Shapes collection, but the size and position are automatically adjusted
when you attach the beginning and end of the connector to other shapes in the collection. Therefore, if you intend to attach a connector to
other shapes, the initial size and position you specify are irrelevant. Likewise, you specify which connection sites on a shape to attach the
connector to when you attach the connector, but using the RerouteConnections method after the connector is attached may change
which connection sites the connector attaches to, making your original choice of connection sites irrelevant.
Example
To figure out which number corresponds to which connection site on a complex shape, you can experiment with the shape
while the macro recorder is turned on and then examine the recorded code; or you can create a shape, select it, and then
run the following example. This code will number each connection site and attach a connector to it.
The following example adds two rectangles to myDocument and connects them with a curved connector.
Databar Object
Represents a data bar conditional formating rule. Applying a data bar to a range helps you see the value of a cell relative to
other cells.
Version Information
Version Added: Excel 2007
Remarks
All conditional formatting objects are contained within a FormatConditions collection object, which is a child of a Range
collection. You can create a data bar formatting rule by using either the Add or AddDatabar method of the
FormatConditions collection.
You use the MinPoint and MaxPoint properties of the Databar object to set the values of the shortest bar and longest
bar of a range of data. These properites return a ConditionValue object, in which you can specify how the thresholds are
evaluated.
Example
The following example creates a range of data and then applies a data bar to the range. You will notice that because there
is an extremely low and high value in the range, the middle values have data bars that are of similiar length. To
disambiguate the middle values, the sample code uses the ConditionValue object to change how the thresholds are
evaluated to percentiles.
Sub CreateDataBarCF()
Range("D1:D9").Select
End Sub
Error Object
Represents a spreadsheet error for a range.
Remarks
Use the Item property of the Errors object to return an Error object.
Once an Error object is returned, you can use the Value property, in conjunction with the Errors property to check
whether a particular error checking option is enabled.
Note
Be careful not to confuse the Error object with error handling features of Visual Basic.
Example
The following example creates a formula in cell A1 referencing empty cells, and then it uses Item(index), where index
identifies the error type, to display a message stating the situation.
Sub CheckEmptyCells()
End Sub
HeaderFooter Object
Represents a single header or footer. The HeaderFooter object is a member of the HeadersFooters collection. The
HeadersFooters collection includes all headers and footers in the specified workbook section.
Version Information
Version Added: Excel 2007
Remarks
You can also return a single HeaderFooter object by using the HeaderFooter property with a Selection object.
Note
Use the DifferentFirstPageHeaderFooter property with the PageSetup object to specify a different first page.
Use the OddAndEvenPagesHeaderFooter property with the PageSetup object to specify different odd and even page
headers and footers. If the OddAndEvenPagesHeaderFooter property is True, you can return an odd header or footer
by using wdHeaderFooterPrimary, and you can return an even header or footer by using
wdHeaderFooterEvenPages.
Example
Use the Add method with the PageNumbers object to add a page number to a header or footer. The following example
adds page numbers to the primary footer in the first section of the active workbook.
With ActiveWorksheet.Sections(1)
.Footers(wdHeaderFooterPrimary).PageNumbers.Add
End With
Hyperlinks Object
Represents the collection of hyperlinks for a worksheet or range.
Remarks
Each hyperlink is represented by a Hyperlink object.
Example
Use the Hyperlinks property to return the Hyperlinks collection. The following example checks the hyperlinks on
worksheet one for a link that contains the word Microsoft.
With Worksheets(1)
.Hyperlinks.Add .Range("E5"), "http://example.microsoft.com"
End With
Validation Object
Represents data validation for a worksheet range.
Example
Use the Validation property to return the Validation object. The following example changes the data validation for cell
E5.
Range("e5").Validation _
.Modify xlValidateList, xlValidAlertStop, "=$A$1:$A$10"
Use the Add method to add data validation to a range and create a new Validation object. The following example adds
data validation to cell E5.
With Range("e5").Validation
.Add Type:=xlValidateWholeNumber, _
AlertStyle:=xlValidAlertInformation, _
Minimum:="5", Maximum:="10"
.InputTitle = "Integers"
.ErrorTitle = "Integers"
.InputMessage = "Enter an integer from five to ten"
.ErrorMessage = "You must enter a number from five to ten"
End With