www.sanketham.tk  k

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”

Returning an Object from a Collection

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.

Set FirstBook = Workbooks.Item(1)
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.

Set FirstBook = Workbooks(1)
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.

ActiveWorkbook.Worksheets.Add.Name = "A New Sheet" With Worksheets("A New Sheet") .Range("A5:A10").Formula = "=RAND()" End With

Predefined Index Values
Some collections have predefined index values you can use to return single objects. Each predefined index value is represented by a constant. For example, you specify an XlBordersIndex constant with the Item property of the Borders collection to return a single border. 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. _ byChange:=Range("C4:E6") SolverAdd cellRef:=Range("F4:F6"). with a module active. click Browse and open Solver. and then select the Solver. The arithmetic relationship between the left and right sides of the constraint. FormulaText) CellRef Required Variant.Activate SolverReset SolverOptions precision:=0. _ formulaText:=100 SolverAdd cellRef:=Range("C4:E6"). Before you use this function. you must establish a reference to the Solver add-in. _ relation:=3. The SolverAdd function is used to add three constraints to the current problem. Cells referenced by CellRef must have final values of either 0 (zero) or 1. Equivalent to clicking Solver in the Data | Analysis group and then clicking Add in the Solver Parameters dialog box. If you choose 4 or 5. SolverAdd(CellRef. A reference to a cell or a range of cells that forms the left side of a constraint. FormulaText Optional Variant. click References on the Tools menu. Relation Required Integer. you can manipulate them with the SolverChange and SolverDelete functions. _ formulaText:=0 SolverAdd cellRef:=Range("C4:E6").xlam in the \office12\library\Solver subfolder. Worksheets("Sheet1").001 SolverOK setCell:=Range("TotalProfit"). If Solver. _ relation:=1.xlam check box under Available References. and FormulaText should not be specified. _ maxMinVal:=1. Relation. In the Visual Basic Editor. _ relation:=4 SolverSolve userFinish:=False SolverSave saveArea:=Range("A33") . Remarks After constraints are added.xlam does not appear under Available References. The right side of the constraint. Example This example uses the Solver functions to maximize gross profit in a business problem. CellRef must refer to adjustable (changing) cells. Relation 1 2 3 4 5 Arithmetic relationship <= = >= Cells referenced by CellRef must have final values that are integers.

Remarks If CellRef and Relation do not match an existing constraint. Cells referenced by CellRef must have final values of either 0 (zero) or 1. FormulaText Optional Variant. you must establish a reference to the Solver add-in. If Solver. and then solves the model again. you must establish a reference to the Solver add-in. click References on the Tools menu. In the Visual Basic Editor. SolverChange(CellRef. with a module active. Example This example loads the previously calculated Solver model stored on Sheet1. click References on the Tools menu. FormulaText) CellRef Required Variant. The right side of the constraint. CellRef must refer to adjustable (changing) cells.xlam in the \office12\library\Solver subfolder. Relation. and FormulaText should not be specified. If Solver. The arithmetic relationship between the left and right sides of the constraint. Relation Required Integer. Before you use this function.xlam check box under Available References.xlam check box under Available References. Equivalent to clicking Solver in the Data | Analysis group and then clicking Delete in the Solver Parameters dialog box. and then select the Solver.xlam in the \office12\library\Solver subfolder. _ formulaText:=200 SolverSolve userFinish:=False   SolverDelete Function Deletes an existing constraint. and then select the Solver.xlam does not appear under Available References. . Before you use this function. If you choose 4 or 5. Relation 1 2 3 4 5 Arithmetic relationship <= = >= Cells referenced by CellRef must have final values that are integers. In the Visual Basic Editor. you must use the SolverDelete and SolverAdd functions to change the constraint. Worksheets("Sheet1"). click Browse and open Solver. with a module active.Activate SolverLoad loadArea:=Range("A33:A38") SolverChange cellRef:=Range("F4:F6"). A reference to a cell or a range of cells that forms the left side of a constraint.  SolverChange Function Changes an existing constraint. changes one of the constraints. _ relation:=1. Equivalent to clicking Solver in the Data | Analysis group and then clicking Change in the Solver Parameters dialog box. click Browse and open Solver.xlam does not appear under Available References.

with a module active. If KeepFinal is 1 or omitted. Can be either 1 or 2. A reference to a cell or a range of cells that forms the left side of a constraint. Worksheets("Sheet1"). click Browse and open Solver. click References on the Tools menu. the final solution values are kept in the changing cells. Cells referenced by CellRef must have final values of either 0 (zero) or 1.xlam does not appear under Available References. CellRef must refer to adjustable (changing) cells. Relation 1 2 3 4 5 Arithmetic relationship <= = >= Cells referenced by CellRef must have final values that are integers. The right side of the constraint. If KeepFinal is 2. FormulaText Optional Variant. and then generates an answer report on a new worksheet. SolverFinish(KeepFinal. and 3 creates a limit report. Relation. and then select the Solver. Worksheets("Sheet1"). you must establish a reference to the Solver add-in. ReportArray) KeepFinal Optional Variant. The kind of report that Excel will create when Solver is finished: 1 creates an answer Example This example loads the previously calculated Solver model stored on Sheet1. In the Visual Basic Editor. Example This example loads the previously calculated Solver model stored on Sheet1. report. The arithmetic relationship between the left and right sides of the constraint. If you choose 4 or 5. solves the model again. Use the Array function to specify the reports you want to display — for example.SolverDelete(CellRef. replacing any former values.xlam in the \office12\library\Solver subfolder. deletes one of the constraints. Before you use this function.3). ReportArray:= Array(1. and then solves the model again. the final solution values are discarded. Relation Required Integer.xlam check box under Available References. and FormulaText should not be specified. and the former values are restored. ReportArray Optional Variant. FormulaText) CellRef Required Variant.Activate SolverLoad LoadArea:=Range("A33:A38") SolverSolve UserFinish:=True . If Solver.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. 2 creates a sensitivity report.

and then select the Solver.Activate SolverLoad loadArea:=Range("A33:A38") SolverSolve userFinish:=True SolverFinishDialog keepFinal:=1.xlam does not appear under Available References. report.3). Can be either 1 or 2. click Browse and open Solver. replacing any former values.xlam does not appear under Available References. and then select the Solver. reportArray:=Array(1)   SolverGet Function Returns information about current settings for Solver.xlam check box under Available References. . If KeepFinal is 1 or omitted. with a module active. Before you use this function. 2 creates a sensitivity report.xlam in the \office12\library\Solver subfolder. ReportArray) KeepFinal Optional Variant. Use the Array function to specify the reports you want to display — for example. 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. solves the model again. click Browse and open Solver. click References on the Tools menu. The number of constraints. In the Visual Basic Editor. if necessary) in the By Changing Cells box.xlam check box under Available References. If Solver. The value in the Value Of box.xlam in the \office12\library\Solver subfolder. The settings are specified in the Solver Parameters and Solver Options dialog boxes. Worksheets("Sheet1"). ReportArray:= Array(1. SolverFinishDialog(KeepFinal. and 3 creates a limit report. and then displays the Finish dialog box with two preset options. the final solution values are kept in the changing cells. In the Visual Basic Editor. A number specifying the type of information you want. but also displays the Solver Results dialog box after solving a problem.SolverFinish KeepFinal:=1. ReportArray Optional Variant. with a module active. If Solver. and 3 represents Value Of. Before you use this function. and the former values are restored. SolverGet(TypeNum. The reference (as a multiple reference. or the #N/A error value if Solver has not been used on the active sheet. The following settings are specified in the Solver Parameters dialog box. you must establish a reference to the Solver add-in. click References on the Tools menu. TypeNum 1 2 3 4 5 Returns The reference in the Set Target Cell box. the final solution values are discarded. you must establish a reference to the Solver add-in. A number corresponding to the Equal To option: 1 represents Max. The kind of report that Excel will create when Solver is finished: 1 creates an answer Example This example loads the previously calculated Solver model stored on Sheet1. If KeepFinal is 2. 2 represents Min. SheetName) TypeNum Required Integer.

in text form. SheetName Optional Variant. subsequent cells . A number corresponding to the type of search: 1 represents Newton. A reference on the active worksheet to a range of cells from which you want to load a complete problem specification. TypeNum 9 10 11 12 13 14 15 16 17 18 19 20 Returns The maximum calculation time. Worksheets("Sheet1"). The integer tolerance value. True if the Assume Linear Model check box is selected. An array of numbers corresponding to the relationships between the left and right sides of the constraints: 1 represents <=. this sheet is assumed to be the active sheet. In the Visual Basic Editor. Before you use this function. A number corresponding to the type of derivatives: 1 represents Forward. False if it is cleared. 4 represents int. The following settings are specified in the Solver Options dialog box. The maximum number of iterations. True if the Assume Non-Negative check box is selected. False if it is cleared. and 2 represents Central. 2 represents =. you must establish a reference to the Solver add-in. If Solver. A number corresponding to the type of estimates: 1 represents Tangent. with a module active.xlam check box under Available References. The first cell in the LoadArea contains a formula for the Set Target Cell box in the Solver Parameters dialog box. SolverLoad(LoadArea) LoadArea Required Variant. Example This example displays a message if you have not used Solver on Sheet1. and 5 represents bin.6 7 8 An array of the left sides of the constraints.xlam does not appear under Available References. the second cell contains a formula for the By Changing Cells box. 3 represents >=. An array of the right sides of the constraints. True if the Use Automatic Scaling check box is selected. True if the Show Iteration Results check box is selected. click References on the Tools menu.xlam in the \office12\library\Solver subfolder.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. in text form. If SheetName is omitted. and then select the Solver. The name of the sheet that contains the Solver model for which you want information. The precision. and 2 represents Quadratic. click Browse and open Solver. The convergence value. and 2 represents Conjugate. False if it is cleared.

MaxMinVal. and ByChange arguments.xlam check box under Available References. click References on the Tools menu.contain constraints in the form of logical formulas. If MaxMinVal is 3. MaxMinVal.Activate SolverReset SolverOptions precision:=0. Worksheets("Sheet1"). Min. SolverOk(SetCell. For more information. and then solves the model again. In the Visual Basic Editor. and then select the Solver. see SolverOptions. ByChange) SetCell Optional Variant. Before you use this function. ByChange Optional Variant. Corresponds to the By Changing Cells box in the Solver Parameters dialog box.xlam in the \office12\library\Solver subfolder. Example This example loads the previously calculated Solver model stored on Sheet1. ValueOf. SolverLoad("Sheet2!A1:A3") loads a model from Sheet2 even if it is not the active sheet. click Browse and open Solver. MaxMinVal 1 2 3 Specifies Maximize Minimize Match a specific value Solver Parameters dialog box. The last cell optionally contains an array of Solver option values. Worksheets("Sheet1"). Corresponds to the Max. Equivalent to clicking Solver in the Data | Analysis group and then specifying options in the Solver Parameters dialog box. you must establish a reference to the Solver add-in. but you must specify the worksheet if it is not the active sheet. _ relation:=1. you must specify the value to which the target cell is matched. The cell or range of cells that will be changed so that you will obtain the desired result in Example This example uses the Solver functions to maximize gross profit in a business problem.001 SolverOK SetCell:=Range("TotalProfit"). and Value options in the Solver Parameters dialog box.xlam does not appear under Available References. Corresponds to the Set Target Cell box in the MaxMinVal Optional Variant. Refers to a single cell on the active worksheet. _ . ValueOf Optional Variant. changes one of the constraints. The range represented by the argument LoadArea can be on any worksheet.Activate SolverLoad loadArea:=Range("A33:A38") SolverChange cellRef:=Range("F4:F6"). If Solver. For example. the target cell. with a module active. _ formulaText:=200 SolverSolve userFinish:=False   SolverOk Function Defines a basic Solver model. The SolverOK function defines a problem by specifying the SetCell.

Corresponds to the Set Target Cell box in the MaxMinVal Optional Variant. If Solver. _ FormulaText:=0 SolverAdd CellRef:=Range("C4:E6").xlam check box under Available References. If MaxMinVal is 3. The cell or range of cells that will be changed so that you will obtain the desired result in Example This example loads the previously calculated Solver model stored on Sheet1. MaxMinVal. Before you use this function.MaxMinVal:=1. ValueOf. the target cell. Min. Worksheets("Sheet1"). ByChange) SetCell Optional Variant. From this point on. click Browse and open Solver. you must establish a reference to the Solver add-in.Activate SolverLoad LoadArea:=Range("A33:A38") SolverReset SolverOKDialog SetCell:=Range("TotalProfit") SolverSolve UserFinish:=False SolverOptions Function . with a module active. but also displays the Solver dialog box. and then displays the Solver Parameters dialog box.xlam in the \office12\library\Solver subfolder. MaxMinVal 1 2 3 Specifies Maximize Minimize Match a specific value Solver Parameters dialog box. _ FormulaText:=100 SolverAdd CellRef:=Range("C4:E6"). and Value options in the Solver Parameters dialog box. _ Relation:=1. Corresponds to the Max. ValueOf Optional Variant. you can use Solver manually. _ ByChange:=Range("C4:E6") SolverAdd CellRef:=Range("F4:F6"). Corresponds to the By Changing Cells box in the Solver Parameters dialog box. SolverOkDialog(SetCell. _ Relation:=4 SolverSolve UserFinish:=False SolverSave SaveArea:=Range("A33")   SolverOkDialog Function Same as the SolverOK function. ByChange Optional Variant. In the Visual Basic Editor. resets all Solver options.xlam does not appear under Available References. you must specify the value that the target cell is matched to. Refers to a single cell on the active worksheet. click References on the Tools menu. _ Relation:=3. and then select the Solver.

If Solver. Precision Optional Variant. and 2 represents central differencing. The value must be a positive integer. False to have Solver calculate without scaling the constraints. True to have Solver scale the constraints to similar orders of magnitude during computation. Scaling. Search. Specifies forward differencing or central differencing for estimates of partial derivatives of the objective and constraint functions: 1 represents forward differencing. you must establish a reference to the Solver add-in. Iterations Optional Variant.True to have Solver pause at each trial solution. but you can enter a value as high as 32. Estimates.True to have Solver assume a lower limit of 0 (zero) for all adjustable (changing) cells that do not have explicit lower limits in the Constraint list box (the cells must contain nonnegative values). AssumeLinear. The default value 100 is adequate for most small problems.xlam in the \office12\library\Solver subfolder. False to have Solver use only the limits specified in the Constraint list box. Conjugate searching is especially useful if stepping through the iterations reveals slow progress between successive trial points.001. Convergence Optional Variant. This function and its arguments correspond to the options in the Solver Options dialog box. This method typically requires more memory than the conjugate search method. which represents the percentage of error allowed in the optimal solution when an integer constraint is used on any element of the problem. Derivatives Optional Variant. . You can try this method if you have a large problem and memory usage is a concern.767. The default value 100 is adequate for most small problems.xlam does not appear under Available References. SolverOptions(MaxTime. the higher the degree of precision you specify (the smaller the number). AssumeLinear Optional Variant.True to have Solver assume that the underlying model is linear. All constraints are satisfied. When the relative change in the target cell value is less than this tolerance for the last five iterations. This argument applies only if integer constraints have been defined. With constraints whose values change rapidly near their limits. Derivatives. and then select the Solver. IntTolerance. StepThru. The default value is 1 (tangent estimates). Estimates Optional Variant. but it should be used only if all the relationships in the model are linear. The maximum number of iterations Microsoft Excel will use in solving the problem. Solver stops and displays the message "Solver converged to the current solution. but it requires fewer iterations. StepThru Optional Variant. If two or more constraints differ by several orders of magnitude. You can adjust the tolerance figure. A decimal number between 0 (zero) and 1 that specifies the degree of integer tolerance.767. A number between 0 (zero) and 1 that specifies the degree of convergence tolerance for the nonlinear Solver. but it typically requires more iterations to reach a particular level of accuracy. The default value is False. This speeds the solution process. A higher degree of tolerance (allowable percentage of error) would tend to speed up the solution process. False to not have Solver pause at each trial solution. and 2 represents quadratic estimates. click Browse and open Solver. is the default search method. Use the Search options to specify the search algorithm that will be used at each iteration to decide which direction to search in: 1 represents the Newton search method. this may improve the results for highly nonlinear problems. The maximum amount of time (in seconds) Microsoft Excel will spend solving the problem. The default value is 1 (forward differencing). the more time Solver will take to reach solutions. Tangent estimates use linear extrapolation from a tangent vector. The value must be a positive integer. The default precision is 0. but you can enter a value as high as 32. which uses a quasi-Newton method. A smaller number of decimal places (for example. click References on the Tools menu. but it may help with problems that generate a message saying that Solver could not improve the solution. The default value is False. Conjugate gradient searching requires less memory than the Newton search method. In the Visual Basic Editor. Newton. Quadratic estimates use quadratic extrapolation.0001) indicates a lower degree of precision. AssumeNonNeg) MaxTime Optional Variant. you should use central differencing. 0.Allows you to specify advanced options for your Solver model. In general. Central differencing requires more worksheet recalculations. and 2 represents the conjugate search method.000001." AssumeNonNeg Optional Variant. Convergence. A number between 0 (zero) and 1 that specifies the degree of precision to be used in solving the problem. IntTolerance Optional Variant. This is useful when the inputs (in the By Changing Cells box in the Solver Parameters dialog box) and outputs (in the Set Target Cell and Subject to the Constraints boxes in the Solver Parameters dialog box) have large differences in magnitude — for example. Search Optional Variant. Example This example sets the Precision option to . Scaling Optional Variant. Iterations.xlam check box under Available References. maximizing percentage of profit based on million-dollar investments. Precision. You can pass Solver a macro to run at each pause by using the ShowRef argument of the SolverSolve function. The default value is False. with a module active. Specifies the approach used to obtain initial estimates of the basic variables in each onedimensional search: 1 represents tangent estimates. Before you use this function.

_ FormulaText:=100 SolverAdd CellRef:=Range("C4:E6"). Before you use this function. If Solver. _ ByChange:=Range("C4:E6") SolverAdd CellRef:=Range("F4:F6"). click References on the Tools menu. _ Relation:=3.Activate SolverReset SolverOptions Precision:=0. Equivalent to clicking Reset All in the Solver Parameters dialog box. with a module active. _ ByChange:=Range("C4:E6") SolverAdd CellRef:=Range("F4:F6"). _ Relation:=1. you must establish a reference to the Solver add-in.001 SolverOK SetCell:=Range("TotalProfit"). _ MaxMinVal:=1. _ Relation:=3. In the Visual Basic Editor. _ MaxMinVal:=1. The SolverReset function is called automatically when you call the SolverLoad function.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").Worksheets("Sheet1"). click Browse and open Solver.xlam does not appear under Available References. _ FormulaText:=0 SolverAdd CellRef:=Range("C4:E6"). _ Relation:=1.Activate SolverReset SolverOptions Precision:=0. and then select the Solver. _ FormulaText:=100 SolverAdd CellRef:=Range("C4:E6"). _ FormulaText:=0 .001 SolverOK SetCell:=Range("TotalProfit"). _ 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.xlam check box under Available References.

_ MaxMinVal:=1. Before you use this function.xlam in the \office12\library\Solver subfolder.xlam does not appear under Available References. _ Relation:=4 SolverSolve UserFinish:=False SolverSave SaveArea:=Range("A33")   SolverSave Function Saves the Solver problem specifications on the worksheet. Example This example uses the Solver functions to maximize gross profit in a business problem. For example. you must establish a reference to the Solver add-in. and then select the Solver. .Activate SolverReset SolverOptions Precision:=0. SolverSave(SaveArea) SaveArea Required Variant. In the Visual Basic Editor. click References on the Tools menu. with a module active. Equivalent to clicking Solve in the Solver Parameters dialog box. _ Relation:=3. _ FormulaText:=100 SolverAdd CellRef:=Range("C4:E6"). click Browse and open Solver. The SolverSave function saves the current problem to a range on the active worksheet. _ Relation:=1. _ Relation:=4 SolverSolve UserFinish:=False SolverSave SaveArea:=Range("A33")   SolverSolve Function Begins a Solver solution run. If Solver. _ FormulaText:=0 SolverAdd CellRef:=Range("C4:E6"). SolverSave("Sheet2!A1:A3") saves the model on Sheet2 even if Sheet2 is not the active sheet. The range represented by the SaveArea argument can be on any worksheet.SolverAdd CellRef:=Range("C4:E6"). The range of cells where the Solver model is to be saved.xlam check box under Available References. _ ByChange:=Range("C4:E6") SolverAdd CellRef:=Range("F4:F6"). Worksheets("Sheet1").001 SolverOK SetCell:=Range("TotalProfit"). but you must specify the worksheet if it is not the active sheet.

_ Relation:=3. If Solver.xla add-in. In the Visual Basic Editor.xlam does not appear under Available References. methods.xlam check box under Available References. Reference) . False or ShowRef Optional Variant. SQLBind specifies where results are placed when they’re retrieved with SQLRetrieve or SQLRetrieveToFile.001 SolverOK SetCell:=Range("TotalProfit"). _ FormulaText:=100 SolverAdd CellRef:=Range("C4:E6").True to return the results without displaying the Solver Results dialog box. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLBind and the other ODBC functions in the Xlodbc. The SolverSolve function begins the Solver solution run. You can pass the name of a macro (as a string) as the ShowRef argument. or to place the result set columns in nonadjacent worksheet columns.Before you use this function. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. Used only if True is passed to the StepThru argument of the SolverOptions function. click Browse and open Solver. This macro is then called whenever Solver returns omitted to return the results and display the Solver Results dialog box. SQLBind(ConnectionNum. _ MaxMinVal:=1.xlam in the \office12\library\Solver subfolder. _ ByChange:=Range("C4:E6") SolverAdd CellRef:=Range("F4:F6"). _ Relation:=1.Activate SolverReset SolverOptions Precision:=0.xla add-in. with a module active. Column. an intermediate solution. This function is contained in the Xlodbc. and then select the Solver. Before you use the function. you must establish a reference to the Solver add-in. Worksheets("Sheet1"). Use SQLBind to change the column order of the result set from a query. _ Relation:=4 SolverSolve UserFinish:=False SolverSave SaveArea:=Range("A33")   SQLBind Function It is recommended that you use the objects. click References on the Tools menu. _ FormulaText:=0 SolverAdd CellRef:=Range("C4:E6"). SolverSolve(UserFinish. ShowRef) UserFinish Optional Variant. Example This example uses the Solver functions to maximize gross profit in a business problem.

SQLBind returns Error 2015. Column 0 (zero) contains bind results. Columns in the result set are numbered from left to right.ConnectionNum Required. If SQLBind is unable to bind the column to the cell in the specified reference. A binding remains valid as long as the connection specified by Call SQLBind after you call SQLOpen and SQLExecQuery. ConnectionNum is open. Use SQLBind for each column in the result set. The column number of the result set you want to bind. If you omit Column. output2 SQLRetrieve chan SQLClose chan   SQLClose Function It is recommended that you use the objects. and then it uses the SQLBind function to display only the fourth and ninth columns of the query result set (the product name and the quantity on order) on Sheet1. If ConnectionNum is not valid or if you try to bind a cell that is unavailable. Example This example runs a query on the Northwind database. it returns Error 2042. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLClose and the other ODBC functions in the Xlodbc. starting with 1. . queryString Set output1 = Worksheets("Sheet1"). Use SQLBind if you want the results from different columns to be placed in disjoint worksheet areas. methods. Reference Optional. 9. If Reference is omitted.dbf WHERE (product. Reference.Range("A1") Set output2 = Worksheets("Sheet1"). If Reference refers to more than a single cell. databaseName = "Northwind" queryString = _ "SELECT * FROM product.xla add-in. SQLBind returns Error 2023. The unique connection ID (returned by SQLOpen) of the data source for which you want to Column Optional. 4. binding is removed for the column. A Range object that specifies the location of a single cell on a worksheet where you want the results to be bound. If SQLRetrieve does not have a destination parameter. You can return the row numbers by binding column 0 (zero). but before you call SQLRetrieve or SQLRetrieveToFile. Calls to SQLBind do not affect results that have already been retrieved.ON_ORDER<>0)" chan = SQLOpen("DSN=" & databaseName) SQLExecQuery chan. Return Value This function returns an array that lists the bound columns for the current connection. SQLBind places the result set in the location indicated by 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. output1 SQLBind chan. all bindings for ConnectionNum are removed.Range("B1") SQLBind chan. row numbers for the result set. by column number.

If SQLClose is unable to disconnect from the data source. is a list of all products that are currently on order. Before you use the function. SQLClose(ConnectionNum) ConnectionNum Required.SQLClose closes a connection to an external data source. It does not provide information about Microsoft Excel errors. This function is contained in the Xlodbc. databaseName = "Northwind" queryString = _ "SELECT * FROM product.xla add-in. displayed on Sheet1. SQLError returns detailed error information when it’s called after one of the other ODBC functions fails. The unique connection ID of the data source you want to disconnect from. this function returns Error 2015. Example This example runs a query on the Northwind database.ON_ORDER<>0)" chan = SQLOpen("DSN=" & databaseName) SQLExecQuery chan. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. This function is contained in the Xlodbc. To make the error information available. SQLError provides detailed error information only about errors that occur when an ODBC function fails. Before you use the function. it cannot return error information. call the SQLError function. . methods. . it returns Error 2042. SQLError returns detailed error information in a two-dimensional array in which each row describes one error. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLError and the other ODBC functions in the Xlodbc. this function returns 0 (zero) and the connection ID is no longer valid. . If ConnectionNum is not valid. SQLError() Return Value If there are errors.xla add-in. True SQLClose chan   SQLError Function It is recommended that you use the objects. If SQLError itself fails. The result of the query.dbf WHERE (product.Range("A1") SQLRetrieve chan.xla add-in. output. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. queryString Set output = Worksheets("Sheet1"). Return Value If the connection is successfully closed. Error information is defined and stored in memory whenever an ODBC function fails.

QueryText) ConnectionNum Required.Cells(1. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor.xla add-in. or DELETE Any other valid SQL statement Return value The number of columns in the result set The number of rows affected by the statement 0 (zero) If SQLExecQuery is unable to execute the query on the specified data source. SQLExecQuery executes only the query.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. Use SQLRetrieve or SQLRetrieveToFile to get the results. as shown in the following table. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLOpen and the other ODBC functions in the Xlodbc. A text message that describes the error. this function returns only Error 2042. it returns Error 2042. SQL statement SELECT UPDATE. If a function call generates multiple errors. The unique connection ID returned by SQLOpen that identifies the data source you want to the specific driver.Formula = returnArray(i) Next i SQLClose chan   SQLExecQuery Function It is recommended that you use the objects. 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). Return Value The value returned by SQLExecQuery depends on the SQL statement. SQLError creates a row for each error. This function is contained in the Xlodbc. QueryText Required. . i). 1) To UBound(returnArray. The query must follow the SQL syntax guidelines for query. chan = SQLOpen("DSN=Nortwind") returnArray = SQLError() For i = LBound(returnArray. The error information is displayed on Sheet1. Before you use the function. If ConnectionNum isn’t valid. SQLExecQuery returns Error 2015. The query to be executed on the data source. If there are no errors from a previous ODBC function call.xla add-in. SQLExecQuery(ConnectionNum. SQLExecQuery executes a query on a data source with a connection that has been established with SQLOpen. INSERT. 1) Worksheets("Sheet1"). methods.

QualifierText) ConnectionNum Required. which you want information. If you call SQLExecQuery using a previously used connection ID.xla add-in. True SQLClose chan   SQLGetSchema Function It is recommended that you use the objects. Before you use the function. The unique connection ID of the data source you connected to by using SQLOpen and for TypeNum Required. The name of the DBMS that the data source uses. A list of columns in a particular table and their ODBC SQL data types. or "Schema".xla add-in. The result of the query. methods. . The terminology used by the data source to refer to the owners. The first field contains the name of the column. The unique connection ID returned by SQLOpen is used by SQLExecQuery to send queries to the data source. The user ID of the current user. is a list of all products that are currently on order. Value 1 2 3 4 5 6 7 8 9 10 11 Meaning A list of all the available data sources. Example This example runs a query on the Northwind database. . you must establish a connection to a data source by using SQLOpen. Specifies the type of information you want returned. displayed on Sheet1. SQLGetSchema returns information about the structure of the data source on a particular connection. output.Range("A1") SQLRetrieve chan.ON_ORDER<>0)" chan = SQLOpen("DSN=" & databaseName) SQLExecQuery chan.Remarks Before calling SQLExecQuery. TypeNum. in a two-dimensional array. . The name of the current database. A list of owners in a database on the current connection. queryString Set output = Worksheets("Sheet1"). A list of databases on the current connection. The name of the data source defined during setup or defined by using the ODBC Control Panel Administrator.dbf WHERE (product. ORACLE or SQL Server. The server name for the data source. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLGetSchema and the other ODBC functions in the Xlodbc. any pending results on that connection are replaced by the new results. For example. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. This function is contained in the Xlodbc. For example "owner". "Authorization ID". A list of tables for a given owner and database on the current connection. SQLGetSchema(ConnectionNum. as shown in the following table. databaseName = "Northwind" queryString = _ "SELECT * FROM product. the second field is the column’s ODBC SQL data type.

or "procedure". this function returns Error 2015.xla add-in. DriverPrompt) . OutputRef. This function is contained in the Xlodbc. For example. The syntax consists of the database name followed by the owner's name. for example. "database procedure".12 13 14 The terminology used by the data source to refer a table For example.OwnerName". The terminology used by the data source to refer to a procedure. databaseName = "Northwind" chan = SQLOpen("DSN=" & databaseName) dsName = SQLGetSchema(chan. SQLGetSchema returns the names of the table owners in that database. and 5. A string that qualifies the search. SQLGetSchema returns information about the columns in the table. "stored procedure". 4. Both a database name and an owner name.xla add-in. SQLOpen establishes a connection to a data source. "database" or "folder". you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. as shown in the following table. 4 5 Return Value The return value from a successful call to SQLGetSchema depends on the type of information that’s requested. If ConnectionNum isn’t valid. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLOpen and the other ODBC functions in the Xlodbc. 8) dsDBMS = SQLGetSchema(chan. 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. For example. TypeNum 3 QualifierText The name of the database in the current data source. If SQLGetSchema cannot find the requested information. 9) MsgBox "Database name is " & dsName & ". QualifierText Optional. "DatabaseName. methods. it returns Error 2042. The name of a table. and its DBMS is " & dsDBMS SQLClose chan   SQLOpen Function It is recommended that you use the objects. This function returns an array of table names that are located in the given database and owned by the given owner. SQLOpen(ConnectionStr. Included only for the TypeNum values 3. with a period separating the two. Before you use the function. "table" or "file". The terminology used by the data source to refer to a qualifier.

such as user ID and passwords. SQLOpen uses 2 as the default. must follow the driver's format. displayed on Sheet1. SQLOpen returns a unique connection ID number. The same as 2 except that dialog box options that aren’t required are dimmed (unavailable). If the connection isn’t successful. methods. . Use one of the values described in the following table. True SQLClose Chan   SQLRequest Function It is recommended that you use the objects.dbf WHERE (product. DatabaseName = "Northwind" QueryString = _ "SELECT * FROM product. A Range object (must be a single cell) that contains the completed connection string. Supplies the information required by the driver being used to connect to a data source. The driver dialog box isn’t displayed. OutputRef. OutputRef Optional. which options are available in it. All dialog box options are available. You must define the data source name (DSN) used in ConnectionStr before you try to connect to it. ConnectionStr supplies the data source name and other information. Example This example runs a query on the Northwind database. QueryString Set output = Worksheets("Sheet1"). The result of the query. DriverPrompt. This function is contained in the Xlodbc. QueryText. If DriverPrompt is omitted. Additional error information is placed in memory for use by SQLError. Output. SQLOpen returns an error. DriverPrompt Optional. Value 1 2 3 4 Meaning The driver dialog box is always displayed. SQLRequest connects to an external data source and runs a query from a worksheet. Before you use the function.xla add-in. Return Value If successful. If SQLOpen is unable to connect using the information you provide. Use the connection ID number with the other ODBC functions.ON_ORDER<>0)" Chan = SQLOpen("DSN=" & DatabaseName) SQLExecQuery Chan. if it is. The driver dialog box is displayed only if information provided by the connection string and the data source specification aren’t sufficient to complete the connection. SQLRequest(ConnectionStr.ConnectionStr Required. .Range("A1") SQLRetrieve Chan. you must establish a reference to the add-in by using the References command (on the Tools menu) in the Visual Basic Editor. Use OutputRef when you want SQLOpen to return the completed connection string to a worksheet.xla add-in. that the driver requires to make a connection. it returns Error 2042. and then it returns the result of the query as an array. Specifies whether the driver dialog box is displayed and. is a list of all products that are currently on order. ColNamesLogical) . and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLRequest and the other ODBC functions in the Xlodbc.

it returns an error. Specifies whether the driver dialog box is displayed and which options are available. _ Worksheets("Sheet1").REQUEST macro function. Use one of the values described in the following table. must follow the driver's format. it returns Error 2042. The result of the query. Value 1 2 3 4 Meaning The driver dialog box is always displayed. True) For i = LBound(returnArray. The SQLRequest function also writes the full connection string to Sheet2.driver being used to connect to a data source. If SQLRequest is unable to access the data source using ConnectionStr. 2) Worksheets("Sheet1"). You must define the data source name (DSN) used in ConnectionStr before you try to connect to it. Dialog box options that aren’t required are dimmed (unavailable). The driver dialog box is displayed only if information provided by the connection string and the data source specification is not sufficient to complete the connection. Example This example runs a query on the Northwind database. OutputRef Optional. Remarks The arguments to the SQLRequest function are in a different order than the arguments to the SQL. The driver dialog box is displayed only if information provided by the connection string and the data source specification is not sufficient to complete the connection.ON_ORDER<>0)" returnArray = SQLRequest("DSN=" & databaseName. Return Value If this function completes all of its actions. it returns Error 2042. DriverPrompt Optional. If ColNamesLogical is omitted. If SQLRequest is unable to complete all of its actions. _ 2.dbf WHERE (product. The SQL statement you want to execute on the data source. 2) To UBound(returnArray. it returns an error value and places the error information in memory for SQLError. If SQLRequest is unable to execute QueryText on the specified data source.Cells(i. If the connection is not successful. True to have the column names returned as the first row of results. databaseName = "Northwind" queryString = _ "SELECT * FROM product.Formula = _ returnArray(i. j) Next j . displayed on Sheet1. it returns an array of query results or the number of rows affected by the query. Supplies information (such as the data source name. 1) For j = LBound(returnArray. If SQLRequest is unable to access the data source using connectionStr. False to not have the column names returned. 1) To UBound(returnArray. user ID. and passwords) required by the ColNamesLogical Optional. j). The dialog box isn’t displayed. SQLRequest uses 2 as the default. ConnectionStr Required. A Range object (must be a single cell) where you want the completed connection string to be placed. QueryText Required. is a list of all products that are currently on order. All dialog box options are available. the default value is False. _ queryString. it returns Error 2042.Range("A1"). If DriverPrompt is omitted.

The name of each range is the resulting column name. When there are no more rows in the result set. You can retrieve extra rows by using SQLRetrieve again and setting FetchFirstLogical to False. If SQLRetrieve is unable to retrieve the results on the specified data source or if there are no results pending. and have the results pending. This function is contained in the Xlodbc. The unique connection ID returned by SQLOpen and for which you have pending query results that were generated by SQLExecQuery. True to have the column names be returned as the first row of results. 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. FetchFirstLogical) ConnectionNum Required.xla add-in. Before using SQLRetrieve. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLRetrieve and the other ODBC functions in the Xlodbc. The maximum number of columns returned to the worksheet. NamedRngLogical Optional. SQLRetrieve can be called repeatedly to return the next set of rows until all the result rows have been returned.Next i   SQLRetrieve Function It is recommended that you use the objects. SQLRetrieve places data in the selected rows but doesn’t discard the additional rows. you must establish a connection with SQLOpen. the bindings established by previous calls to SQLBind are used to return results. the results are discarded. MaxRows. The default value is False. True to have the first column in the result set contain row numbers. SQLRetrieve returns Error 2023. If MaxRows is omitted. If MaxRows specifies more rows than are available in the results. MaxColumns. starting at DestinationRef. DestinationRef. You can also retrieve row numbers by binding column 0 (zero) with SQLBind. The order in which the data source returns the columns determines column position. The default value is False. If FetchFirstLogical is False. SQLRetrieve(ConnectionNum.xla add-in. all the results are returned. MaxRows Optional. A Range object that specifies where the results should be placed. ColNamesLogical Optional. starting at DestinationRef. you must do the following: . If MaxColumns is omitted. Return Value SQLRetrieve returns the number of rows in the result set. RowNumsLogical Optional. If DestinationRef is omitted. SQLRequest returns 0 (zero). all the rows in the results are returned. without confirmation. RowNumsLogical. If MaxColumns specifies more columns than are available in the result. it returns Error 2042. True to have each column of the results be declared as a named range on the worksheet. SQLRetrieve returns all the pending results in that cell and in the cells to the right of and below it. This function overwrites any values in the cells. Remarks Before calling SQLRetrieve. SQLRetrieve retrieves all or part of the results from a previously executed query. If a particular result column hasn’t been bound and DestinationRef is omitted. NamedRngLogical. Before you use the function. Allows you to request results from the beginning of the result set. set FetchFirstLogical to True. methods. If DestinationRef refers to a single cell. ColNamesLogical. set FetchFirstLogical to False in subsequent calls. If no data is found. SQLRetrieve discards the rightmost result columns until the results fit the specified size. The named range includes only the rows that are returned with SQLRetrieve. MaxColumns Optional. If no bindings exist for the current connection. SQLRetrieve places data in the columns for which data is available and clears the additional columns.FetchFirstLogicall Optional. If you want to retrieve results from the beginning of the result set. SQLExecQuery returns Error 2015. To retrieve additional rows from the result set. False or omitted to have the column names not be returned. execute a query with SQLExecQuery. If ConnectionNum is not valid. If MaxRows specifies fewer rows than are available in the results. If MaxColumns specifies fewer columns than are available in the result. SQLRetrieve returns 0 (zero). Used only when DestinationRef is included in the function call. The maximum number of rows to be returned to the worksheet. SQLRetrieve places data in the rows for which data is available and clears the additional rows. False or omitted to have the row numbers not be returned.

If the file doesn’t exist. SQLRetrieveToFile retrieves all the results from a previously executed query and places them in a file. output. True to have the column names be returned as the first row of data. True SQLClose chan   SQLRetrieveToFile Function It is recommended that you use the objects.1. SQLRetrieveToFile returns the query results. Before you use the function.ON_ORDER<>0)" chan = SQLOpen("DSN=" & databaseName) SQLExecQuery chan. it returns Error 2042 and doesn’t write the file. ColumnDelimiter) the file exists. Use the connection ID returned in SQLOpen to send a query with SQLExecQuery.Range("A1") SQLRetrieve chan. its contents are replaced with the query results. and then returns the number of rows that were written to the file. ColumnDelimiter Optional. you must have established a connection with a data source by using SQLOpen. and the individual rows are separated by a carriage return. The unique connection ID returned by SQLOpen and for which you have pending query results that were generated by SQLExecQuery. .dbf WHERE (product. Establish a connection with a data source by using SQLOpen.csv (comma-separated value) file format. executed a query by using SQLExecQuery. If the file specified by Destination cannot be opened. The result of the query. 2." to specify a semicolon delimiter. writes them to a file. SQLRetrieveToFile creates and opens the file and fills it with the results. If ConnectionNum isn’t valid. SQLRetrieveToFile returns Error 2042. . . ColNamesLogical. The format of the data in the file is compatible with the Microsoft Excel . A string that specifies the name and path of the file where you want to place the results. and have the results of the query pending. If Return Value If successful. SQLRetrieveToFile returns Error 2042. databaseName = "NorthWind" queryString = _ "SELECT * FROM product. This function is contained in the Xlodbc. To use this function. is a list of all products that are currently on order.xla add-in. methods. ConnectionNum Required. you must establish a reference to the add-in by using the References command (in the Tools menu) in the Visual Basic Editor. SQLRetrieveToFile(ConnectionNum. Columns are separated by the character specified by ColumnDelimiter. Destination. the list separator character is used. and properties in the Microsoft ActiveX Data Objects (ADO) library instead of SQLRetrieveToFile and the other ODBC functions in the Xlodbc. If SQLRetrieveToFile is unable to retrieve the results. For example. If you omit ColumnDelimiter.xla add-in." to specify a comma delimiter. Example This example runs a query on the Northwind database. ColNamesLogical Optional. or use ". A string that specifies the character used to separate the elements in each row. False or omitted to have the column names not be returned. use ". displayed on Sheet1. queryString Set output = Worksheets("Sheet1"). SQLExecQuery returns Error 2015. If there are no pending results on the connection.Destination Required.

is written as the delimited text file Output. You can easily control the new workbook by using the object variable. In the following example. which is a list of all products that are currently on order.SaveAs Filename:="Allsales. True SQLClose chan         How to: Create a Workbook To create a workbook in Visual Basic. Use the connection ID returned by SQLOpen to send a query with SQLExecQuery. The following procedure creates a workbook. Sub AddNew() Set NewBook = Workbooks. use the Add method.ON_ORDER<>0)" chan = SQLOpen("DSN=" & databaseName) SQLExecQuery chan. Example This example runs a query on the Northwind database. 2.Add With NewBook . the Workbook object returned by the Add method is assigned to an object variable.TXT".Title = "All Sales" . newBook.Subject = "Sales" . databaseName = "Northwind" queryString = _ "SELECT * FROM product.txt in the current folder. Establish a connection with a data source by using SQLOpen. Next. The result of the query. where N is the next available number. Microsoft Excel automatically names the workbook BookN. queryString SQLRetrieveToFile chan.Add End Sub A better way to create a workbook is to assign it to an object variable.Remarks Before calling SQLRetrieveToFile.dbf WHERE (product.xls" End With End Sub . you must do the following: 1. several properties of newBook are set. Sub AddOne() Workbooks. The new workbook becomes the active workbook. "OUTPUT.

chart.Activate DialogSheets("Dialog1"). Sub ActivateChart() Sheets("Chart1"). The following statements activate various sheets in the active workbook.Activate End Sub     How to: Refer to Sheets by Name You can identify sheets by name using the Worksheets and Charts properties. based on the position of its sheet tab (counting from the left) among sheets of the same type.Activate End Sub If you want to work with all types of sheets (worksheets. and dialog sheets). Worksheets("Sheet1"). Sub FourthOne() Sheets(4). modules. charts.xls") End Sub   . it becomes a member of the Workbooks collection. use the Sheets property. Sub OpenUp() Workbooks. the Sheets collection contains all of these. or dialog sheet.Activate Charts("Chart1").Activate End Sub   Opening a Workbook When you open a workbook using the Open method. The following procedure activates sheet four in the workbook. Sub FirstOne() Worksheets(1).Open("C:\MyFolder\MyBook. module.Activate You can use the Sheets property to return a worksheet. The following procedure opens a workbook named MyBook.xls located in the folder named MyFolder on drive C. The following example activates the sheet named "Chart1" in the active workbook.  How to: Refer to Sheets by Index Number An index number is a sequential number assigned to a sheet. The following procedure uses the Worksheets property to activate worksheet one in the active workbook.

htm". content. as shown in the following example. You can also edit HTML files directly in Excel. worksheet. range. you can use the Publish method to save the workbook.PixelsPerInch = 96 End With With . The DefaultWebOptions object contains application-level properties. graphics formats. To do this.FileName = "C:\Reports\1998_Q1. which saves the active workbook as C:\Reports\myfile. query table. browser support.htm" .Saving Documents as Web Pages In Microsoft Excel.DefaultWebOptions . overriding the application-level default setting. and encoding of the HTML document by setting properties of the DefaultWebOptions object and the WebOptions object. The following example sets various application-level properties and then sets the AllowPNG property of the active workbook. or AutoFilter range to a Web page.AllowPNG = True . With ActiveWorkbook With .Publish End With End With You can also save the files directly to a Web server.SaveAs _ Filename:="C:\Reports\myfile.htm.htm. ActiveWorkbook. PivotTable report.htm. These settings are overridden by any workbook-level property settings that have the same names (these are contained in the WebOptions object). The following example saves a range to a Web server. print area.WebOptions.homepage. worksheet. you can save a workbook. file organization. _ FileFormat:=xlHTML Customizing the Web Page You can customize the appearance. the example saves the range as "C:\Reports\1998_Q1. Saving a Document as a Web Page Saving a document as a Web page is the process of creating and saving an HTML file and any supporting files.RelyonVML = True . range. giving the Web page the URL address http://example. or AutoFilter range to a Web page.PixelsPerInch = 96 End With With ActiveWorkbook .RelyonVML = True . editing support. chart.com/annualreport.AllowPNG = False With . print area.WebOptions . query table. Finally. After setting the attributes. screen resolution. PivotTable report.PublishObjects(1) . chart. use the SaveAs method.PublishObjects(1) ." With Application.

.FileName = _ "http://example.homepage.com/annualreport.htm" .Publish End With End With

Opening an HTML Document in Microsoft Excel
To edit an HTML document in Excel, first open the document by using the Open method. The following example opens the file "C:\Reports\1997_Q4.htm" for editing.

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.

 
Formatting and VBA Codes for Headers and Footers
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 code &L &C &R &E &X &Y &B &I &U &S &"fontname" &nn &color VBA code &D &T &F &A &P &P+number &P-number &&

Description Left aligns the characters that follow. Centers the characters that follow. Right aligns the characters that follow. Turns double-underline printing on or off. Turns superscript printing on or off. Turns subscript printing on or off. Turns bold printing on or off. Turns italic printing on or off. Turns underline printing on or off. Turns strikethrough printing on or off. Prints the characters that follow in the specified font. Be sure to include the double quotation marks. Prints the characters that follow in the specified font size. Use a two-digit number to specify a size in points. Prints the characters in the specified color. User supplies a hexidecimal color value. Description Prints the current date. Prints the current time. Prints the name of the document. Prints the name of the workbook tab. Prints the page number. Prints the page number plus the specified number. Prints the page number minus the specified number. Prints a single ampersand.

&N &Z &G

Prints the total number of pages in the document. Prints the file path. Inserts an image.

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 End Sub &B&ITime:&I&B&T"

   
How to: Reference Cells and Ranges
A common task when using Visual Basic is to specify a cell or range of cells and then do something with it, such as enter a formula or change the format. You can usually do this in one statement that identifies the range and also changes a property or applies a method. A Range object in Visual Basic can be either a single cell or a range of cells. The following topics show the most common ways to identify and work with Range objects.

 
How to: Refer to All the Cells on the Worksheet
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

 
How to: Refer to Cells and Ranges by Using A1 Notation
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") Range("A1:B5") Range("C5:D9,G9:H16") Range("A:A") Range("1:1") Range("A:C") Range("1:5") Range("1:1,3:3,8:8") Range("A:A,C:C,F:F")

Cell A1 Cells A1 through B5 A multiple-area selection Column A Row 1 Columns A through C Rows 1 through 5 Rows 1, 3, and 8 Columns A, C, and F

 
How to: Refer to Cells by Using a Range Object
If you set an object variable to a Range object, you can easily manipulate the range by using the variable name. The following procedure creates the object variable myRange and then assigns the variable to range A1:D5 on Sheet1 in the active workbook. Subsequent statements modify properties of the range by substituting the variable name for the Range object.

Sub Random() Dim myRange As Range Set myRange = Worksheets("Sheet1").Range("A1:D5") myRange.Formula = "=RAND()" myRange.Font.Bold = True End Sub

 
How to: Refer to Cells by Using Index Numbers
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

 

G9:H16.B14:D18"). The following example clears the contents of three ranges on Sheet1. and then formats the combined ranges as bold. as shown in the following examples. The following example creates a Range object called myMultipleRange. YourRange. Using the Range Property You can refer to multiple ranges with the Range property by inserting commas between two or more references. Sub MultipleRange() Dim r1. you can easily refer to multiple ranges.Range("C5:D9. Use the Range and Union methods to refer to any group of ranges. defines it as the ranges A1:B2 and C3:D4.Value = 30 End Sub   How to: Refer to Multiple Ranges Using the appropriate method. Sub ClearRanges() Worksheets("Sheet1").[A1:B5]. _ ClearContents End Sub Named ranges make it easier to use the Range property to work with multiple ranges. HisRange").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. r2.ClearContents End Sub Using the Union Method You can combine multiple ranges into one Range object by using the Union method. use the Areas property to refer to the group of ranges selected on a worksheet.ClearContents End Sub Sub SetValue() [MyRange]. The following example works when all three named ranges are on the same sheet. Sub ClearNamed() Range("MyRange. r2) . myMultipleRange As Range Set r1 = Sheets("Sheet1").Range("A1:B2") Set r2 = Sheets("Sheet1"). Sub ClearRange() Worksheets("Sheet1"). You do not have to type the word "Range" or use quotation marks.Range("C3:D4") Set myMultipleRange = Union(r1.

Italic = True End Sub The following example refers to the worksheet-specific range named "Sheet1!Sales" in the workbook named "Report. type a name. Sub FindMultiple() If Selection. and then press ENTER.xls!MyRange" Selection. Sub ClearRange() Application.Goto Reference:="MyBook.Bold = True End Sub Using the Areas Property You can use the Areas property to refer to the selected range or to the collection of ranges in a multiple-area selection.Areas. If there is more than one area. To name a selected range.Count > 1 Then MsgBox "Cannot do this to a multiple selection.ClearContents . Referring to a Named Range The following example refers to the range named "MyRange" in the workbook named "MyBook." Sub FormatRange() Range("MyBook.myMultipleRange.xls. The following procedure counts the areas in the selection. Sub ClearRange() Application.xls]Sheet1!Sales").ClearContents End Sub The following example shows how the same procedure would be written for the active workbook.xls!MyRange")." End If End Sub   How to: Refer to Named Ranges Ranges are easier to identify by name than by A1 notation.xls.Goto Reference:="MyRange" Selection. click the name box at the left end of the formula bar. a warning message is displayed.Font.Font.BorderAround Weight:=xlthin End Sub To select a named range. use the GoTo method." Sub FormatSales() Range("[Report. which activates the workbook and the worksheet and then selects the range.

Font.Next loop. Rows(5)) myUnion.ColorIndex = 27 End If Next c End Sub   How to: Refer to Rows and Columns Use the Rows property or the Columns property to work with entire rows or columns.Bold = True End Sub The following table illustrates some row and column references using the Rows and Columns properties.Rows(1).End Sub Looping Through Cells in a Named Range The following example loops through each cell in a named range by using a For Each. the cell color is changed to yellow.Activate Dim myUnion As Range Set myUnion = Union(Rows(1). three. The following example changes the format of rows one. Sub SeveralRows() Worksheets("Sheet1").Interior. Rows(1) returns row one on Sheet1. Sub RowBold() Worksheets("Sheet1"). Sub ApplyColor() Const Limit As Integer = 25 For Each c In Range("MyRange") If c. The Bold property of the Font object for the range is then set to True. In the following example.. and five on worksheet one in the active workbook to bold. create an object variable and use the Union method. combining multiple calls to the Rows or Columns property. These properties return a Range object that represents a range of cells.Bold = True End Sub .Font.Value > Limit Then c. If the value of any cell in the range exceeds the value of limit.. Reference Meaning Row one All the rows on the worksheet Column one Column one All the columns on the worksheet Rows(1) Rows Columns(1) Columns("A") Columns To work with several rows or columns at the same time. Rows(3).

Using the Cells property.Value = 0 Next Counter End Sub Another easy way to loop through a range is to use a For Each.Value) < 0. One way to loop through a range is to use the For.01 Then c. setting to 0 (zero) any number whose absolute value is less than 0.01 Then c. loops through the range that surrounds the active cell. the variable counter is substituted for the row index. you usually select a cell or cells and then perform an action. such as formatting the cells or entering values in them. setting to 0 (zero) any number whose absolute value is less than 0. Visual Basic automatically sets an object variable for the next cell each time the loop runs. Sub RoundToZero3() For Each c In ActiveCell.01 Then curCell. when run from a worksheet.01.Cells If Abs(c. In the following example. You just need to return the Range object and then set the Formula property to the formula you want.Next loop with the collection of cells specified in the Range property. The procedure loops through the range C1:C20. To do this. For example. if you want to enter a formula in cell D6 using Visual Basic. 3) If Abs(curCell. and run the operation. you combine a looping statement and one or more methods to identify each cell.  Looping Through a Range of Cells When using Visual Basic..Formula = "=SUM(D2:D5)" ..Next loop with the Cells property. you can substitute the loop counter (or other variables or expressions) for the cell index numbers.Value = 0 Next End Sub   Selecting and Activating Cells When you work with Microsoft Excel. you do not need to select the range D6. In Visual Basic.Value) < 0. The following procedure loops through the range A1:D10.Cells If Abs(c.Range("D6").01.Value = 0 Next End Sub If you do not know the boundaries of the range you want to loop through. setting to 0 (zero) any number whose absolute value is less than 0. For example. as shown in the following example.Range("A1:D10"). you can use the CurrentRegion property to return the range that surrounds the active cell. Sub RoundToZero1() For Counter = 1 To 20 Set curCell = Worksheets("Sheet1"). Sub EnterFormula() Worksheets("Sheet1"). one at a time. you often need to run the same block of statements on each cell in a range of cells. Sub RoundToZero2() For Each c In Worksheets("Sheet1").CurrentRegion.. the following procedure.01. it is usually not necessary to select cells before modifying them.Cells(Counter..Value) < 0.

Font.End Sub For examples of using other methods to control cells without selecting them.Select Worksheets("Sheet2"). the Select method will fail unless your procedure activates the worksheet before using the Select method on a range of cells. Sub CopyRow() Worksheets("Sheet1"). If you run your Sub procedure from the module.Copy Worksheets("Sheet2"). Sub Macro1() Sheets("Sheet1"). The macro recorder will often create a macro that uses the Select method and the Selection property. and then select a range (or other object) using the Select method.Font.Paste End Sub .Select Range("A1"). the following procedure copies a row from Sheet1 to Sheet2 in the active workbook. The following Sub procedure was created using the macro recorder.FormulaR1C1 = "Address" Range("A1:B1"). activate or select a sheet. the Selection property returns an object that represents the current selection on the active sheet in the active workbook. you must activate a workbook. Using the Select Method and the Selection Property The Select method activates sheets and objects on sheets.Select ActiveCell. Before you can use the Selection property successfully.Bold = True End With End Sub Selecting Cells on the Active Worksheet If you use the Select method to select cells.Select Worksheets("Sheet2"). For example.Select ActiveCell.Rows(1).Bold = True End Sub The following example accomplishes the same task without activating or selecting the worksheet or cells.Range("A1") = "Name" . be aware that Select works only on the active worksheet. Sub Labels() With Worksheets("Sheet1") . and it illustrates how Select and Selection work together.Range("A1:B1").Rows(1). see How to: Reference Cells and Ranges.FormulaR1C1 = "Name" Range("B1").Select Selection.Range("B1") = "Address" .

"Sheet3". Sub MakeActive() Worksheets("Sheet1"). even when a range of cells is selected. Sub SetValue() Worksheets("Sheet1"). .Range("A1:H1")) End Sub   Working with the Active Cell The ActiveCell property returns a Range object that represents the cell that is active.Borders(xlBottom).Range("A1:H1") _ . Sub FormatSheets() Sheets(Array("Sheet2". "Sheet5")).Select Range("B2"). You can apply any of the properties or methods of a Range object to the active cell. use the Array function to specify two or more sheets to select.Activate ActiveCell.Activate End Sub   Working with 3-D Ranges If you are working with the same range on more than one sheet.Activate Range("A1:D4").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.FillAcrossSheets (Worksheets("Sheet2") _ . as in the following example. The following procedure selects a range and then activates a cell within the range without changing the selection.Activating a Cell Within a Selection You can use the Activate method to activate a cell within a selection.LineStyle = xlDouble Worksheets.Select Range("A1:H1"). There can be only one active cell. The following example formats the border of a 3-D range of cells. Sub FillAll() Worksheets("Sheet2").Select Selection.Value = 35 End Sub Note You can work with the active cell only when the worksheet that it is on is the active sheet.

xlErrValue) For i = 1 To 7 Worksheets("Sheet1").Activate ActiveCell. myArray = Array(xlErrDiv0. Constant xlErrDiv0 xlErrNA xlErrName xlErrNull xlErrNum xlErrRef xlErrValue Error number 2007 2042 2029 2000 2036 2023 2015 Cell error value #DIV/0! #N/A #NAME? #NULL! #NUM! #REF! #VALUE! Example This example inserts the seven cell error values into cells A1:A7 on Sheet1.Value Select Case errval Case CVErr(xlErrDiv0) MsgBox "#DIV/0! error" Case CVErr(xlErrNA) . You can use this example as a framework for a cell-error-value error handler. Worksheets("Sheet1").1)) Next i This example displays a message if the active cell on Sheet1 contains a cell error value. xlErrNA. the following procedure makes B5 the active cell and then formats it as bold. xlErrName.Value) Then errval = ActiveCell.Moving the Active Cell You can use the Activate method to designate which cell is the active cell.Activate If IsError(ActiveCell.Range("B5").Value = CVErr(myArray(i . For example.Cells(i. The cell error values can be one of the following XlCVError constants.Bold = True End Sub   Cell Error Values 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. _ xlErrNum.Activate Worksheets("Sheet1").Font. 1). xlErrRef. Sub SetActive() Worksheets("Sheet1"). xlErrNull.

Control and Dialog Box Events All controls have a predefined set of events. Setting Control Properties Right-click a control in design mode and click Properties to display the Properties window. How to: Create a Custom Dialog Box Use the following procedure to create a custom dialog box: 1. . Create a User Form On the Insert menu in the Visual Basic Editor.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 How to: Add Controls to a Document To add controls to a document. Add Controls to a User Form Find the control you want to add in the Toolbox and drag the control onto the form. Drag an adjustment handle of the control until the control's outline is the size and shape you want. Initializing Control Properties You can initialize controls in a procedure before you show a form. display the Control Toolbox. How to: Add Controls to a User Form To add controls to a user form. 3. 4. You can write event procedures that run when the events occur. For example. a command button has a Click event that occurs when the user clicks the command button. 5. find the control you want to add in the Toolbox. 2. or you can add code to the Initialize event of the form. and then drag an adjustment handle on the control until the control's outline is the size and shape you want. and then click on the document. click the control you want to add. drag the control onto the form. click UserForm.

ScrollColumn = t. 7. These properties can be set and returned using the ActiveX control name.Row . set the Caption property.Column . The following example scrolls the workbook window so CommandButton1 is in the upper-left corner. Changes made to the dialog box by the user are lost when the dialog box is closed.ScrollRow = t. ListFillRange. click UserForm on the Insert menu in the Visual Basic Editor. For example.6. Keep the following points in mind when you are working with controls on sheets: In addition to the standard properties available for ActiveX controls. to change the caption on a form. Displaying a Custom Dialog Box Use the Show method to display a UserForm. PrintObject.   ActiveX Controls For more information about a specific control.CommandButton1. behavior. and appearance of the form.   How to: Create a User Form To create a custom dialog box. select a control and click Events at the top of the topic. Using Control Values While Code Is Running Some properties can be set at run time. TopLeftCell. LinkedCell. select an object from the following list. Use the Properties window to change the name. Placement. To create a UserForm. For general information on adding and working with controls. For information about events. you must create a UserForm. Set t = Sheet1. and ZOrder. the following properties can be used with ActiveX controls in Microsoft Excel: BottomRightCell.TopLeftCell With ActiveWindow . CheckBox ComboBox CommandButton Image Label ListBox OptionButton ScrollBar SpinButton TextBox ToggleButton   Using ActiveX Controls on Sheets This topic covers specific information about using ActiveX controls on worksheets and chart sheets. see Using ActiveX Controls on a Document and Creating a Custom Dialog Box.

ActiveX control information is lost." .CommandButton. The following example adds a command button to worksheet 1.Sort Key1:=Range("a1") End Sub You can work around this problem by activating some other element on the sheet before you use the property or method that failed. The controls will work if the user right-clicks the workbook and selects the Open command from the shortcut menu. the following code sorts the range: Private Sub CommandButton1.Activate End Sub 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. use the Add method of the OLEObjects collection.Activate Range("a1:a10").CommandButton1. The Me keyword in an event procedure for an ActiveX control on a sheet refers to the sheet. For example.1". Worksheets(1). For example. Because ActiveX controls are also represented by OLEObject objects in the OLEObjects collection. select the control and set the (Name) property in the Properties window.Caption = "Run" Note that when you use a control name outside the class module for the sheet containing the control. To programmatically add an ActiveX control to a sheet." Sheet1. The following example changes the caption on the control named "CommandButton1. To change the control name you use in Visual Basic code. your Visual Basic code will refer to ActiveX controls by name.Sort Key1:=Range("a1") CommandButton1.0/95 Workbook file format.Click Range("a1").Add "Forms. _ Left:=10. not to the control. The following example sets the left position of the control named "CommandButton1. Private Sub CommandButton1. so the following code fails in a button click event procedure (because the control is still active after the user clicks it).OLEObjects. the Sort method cannot be used when a control is active.End With Some Microsoft Excel Visual Basic methods and properties are disabled when an ActiveX control is activated. you can set control properties using the objects in the collection. Top:=10. When a Microsoft Excel workbook is saved using the Microsoft Excel 5. ActiveX controls are represented by OLEObject objects in the OLEObjects collection (all OLEObject objects are also in the Shapes collection). you must qualify the control name with the sheet name.Click Range("a1:a10"). Width:=100 Using Control Properties with Visual Basic Most often. Adding Controls with Visual Basic In Microsoft Excel. Height:=20.

outline. superscript. orientation. add_indent name_array.OLEObjects("CheckBox1").OLEObjects("CommandButton1"). However. to refer to the control by name. Private Sub chkFinished_Click() ActiveSheet. You use the code name of a control in the names of its event procedures. omit_row. use_rowcol. The following example sets the caption for CommandButton1. When you first add a control to a sheet. you can use the collection to set properties for several controls.Caption = "run me" Because all OLE objects are also members of the Shapes collection. but you still have to use CheckBox1 to return the control from the Shapes or OLEObject collection. _ Object. y_num arrange_num. start_char. desc_text operation_num. and the code name for the control. shadow. color.Worksheets(1).Type = msoOLEControlObject Then s. However. pane_num font. which you can see in the Name box when you view the sheet. the other is not automatically changed to match. normal. vert_align. font_style. If you then change the control code name by typing chkFinished next to (Name) in the Properties window.Shapes If s.Object. wrap. Worksheets(1). order_num. ignore. The following example aligns the left edge of all controls on worksheet 1. background. if you change either the shape name or code name. you must use chkFinished in event procedure names. you must use the shape name. which you can see in the cell to the right of (Name) in the Properties window. not the code name.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.Value = 1 End Sub   Built-In Dialog Box Argument Lists Dialog box constant xlDialogActivate xlDialogActiveCellFont xlDialogAddChartAutoformat xlDialogAddinManager xlDialogAlignment xlDialogApplyNames xlDialogApplyStyle xlDialogAppMove xlDialogAppSize xlDialogArrangeAll xlDialogAssignToObject xlDialogAssignToTool Argument list(s) window_text. macro_ref . For example. addinname_text.Left = 10 Next Using Control Names with the Shapes and OLEObjects Collections An ActiveX control on a sheet has two names: the name of the shape that contains the control. position. size. y_num x_num. when you return a control from the Shapes or OLEObjects collection for a sheet. append_last style_text x_num. as shown in the following example. sync_horiz. underline.OLEObjects("CommandButton1"). sync_vert macro_ref bar_id. char_count name_text. strikethrough. copy_logical horiz_align. For Each s In Worksheets(1). subscript. assume that you add a check box to a sheet and that both the default shape name and the default code name are CheckBox1. active_doc. omit_col. the shape name and code name match.

number_cats. value. trend name_text. number_titles value. category. right. attribute_num. green_value. dependents. calc_save. categories. hidden. max_num. y_primary. show_key rowcol. replace. format. left. size. note validation_num.. categories. left_col. title. right_color. auto_text. gallery_num. plot_by. backcast. shortcut_text.. new_text. legend. step_value. additional_def_args. . font. left. name long. top_row. page_breaks. names. accel_text. z_primary outline. bottom. alignment. y_primary. save_values. formula. bottom. bottom_color type_num. type_of_link ref. protection style_text. outline_color. standard_num type_num source_refs. stop_value. z_title. date_1904. series_num. top. link. pattern. rowcol. alt_form locked. date_num. x_secondary. precedents. intercept. update. type_num. right file_text. password_logical color_num. r_squared. 3d_shading type_num file_text width_num. equation.xlDialogAttachText xlDialogAttachToolbars xlDialogAutoCorrect xlDialogAxes xlDialogAxes xlDialogBorder xlDialogCalculation xlDialogCellProtection xlDialogChangeLink xlDialogChartAddData xlDialogChartLocation xlDialogChartOptionsDataLabels xlDialogChartOptionsDataTable xlDialogChartSourceData xlDialogChartTrend xlDialogChartType xlDialogChartWizard xlDialogCheckboxProperties xlDialogClear xlDialogColorPalette xlDialogColumnWidth xlDialogCombination xlDialogConditionalFormatting xlDialogConsolidate xlDialogCopyChart xlDialogCopyPicture xlDialogCreateNames xlDialogCreatePublisher xlDialogCustomizeToolbar xlDialogCustomViews xlDialogDataDelete xlDialogDataLabel xlDialogDataSeries xlDialogDataValidation xlDialogDefineName xlDialogDefineStyle xlDialogDefineStyle xlDialogDeleteFormat xlDialogDeleteName xlDialogDemote xlDialogDisplay xlDialogDisplay xlDialogEditboxProperties xlDialogEditColor xlDialogEditDelete attach_to_num. standard. protection. x_title. ser_titles. local style_text. titles. zeros. vscroll_logical. top_color. format_text name_text row_col formulas. ref. number. reference. hidden old_text. red_value. max_change. y_secondary x_primary. create_links size_num appearance_num. precision. reserved. capitalize_days x_primary. alt_exp. border. type_num top. color_num. outline. shade. multiline_logical. iter. accel2_text. headings. gridlines. size_num. blue_value shift_num . point_num correct_initial_caps. series type. object_num cell. macro_type. formats category show_option. left_color. type_num. ord_per. function_num. forecast. refers_to. type_num. appearance. y_title.

y_offset. outline. height x_off. name_ref. gap_depth. strikethrough. labels. show_value. active_cell. doughnut_size width. gap_width. edition_name. delete_overlay . pattern. match_case. start_num. object_id. y_align. char_num position_num type_num. copy_ref. vary. doughnut_size x_offset.xlDialogEditionOptions xlDialogEditSeries xlDialogErrorbarX xlDialogErrorbarY xlDialogExternalDataProperties xlDialogExtract xlDialogFileDelete xlDialogFileSharing xlDialogFillGroup xlDialogFillWorkgroup xlDialogFilter xlDialogFilterAdvanced xlDialogFindFile xlDialogFont xlDialogFontProperties xlDialogFormatAuto xlDialogFormatChart xlDialogFormatCharttype xlDialogFormatFont xlDialogFormatFont xlDialogFormatFont xlDialogFormatLegend xlDialogFormatMain xlDialogFormatMove xlDialogFormatMove xlDialogFormatMove xlDialogFormatNumber xlDialogFormatOverlay xlDialogFormatSize xlDialogFormatSize xlDialogFormatText xlDialogFormulaFind xlDialogFormulaGoto xlDialogFormulaReplace xlDialogFunctionWizard xlDialogGallery3dArea xlDialogGallery3dBar xlDialogGallery3dColumn xlDialogGallery3dLine xlDialogGallery3dPie xlDialogGallery3dSurface xlDialogGalleryArea edition_type. strike. overlap. backgd. angle. border. y_pos explosion_num format_text type_num. in_num. shadow. angle. option. up_down. underline. reference x_align. z_ref. hilo. match_case. overlap. minus unique file_text type_num type_num operation. corner find_text. match_byte type_num type_num type_num type_num type_num type_num type_num. hilo. size_num. size_num. look_by. type_num color. view. normal. chart_depth. axis_num. orient_num. outline. drop. reference x_pos. shadow. unique name_text. char_count format_num. color. overlap. size_num font. reference. plot_order include. group_num. series_line. x_ref. underline. bold. at_num. font. superscript. underline. size. appearance. up_down. view. background. object_id_text. dir_num. bold. look_at. by_num. apply. series_line. type. number. font_style. formats series_num. amount. size_num. bold. gap_width. italic. angle. dimension. view. labels. outline. doughnut_size. alignment. list_ref. gap_depth. drop. color. up_down. start_char. series_num. subscript. shadow. char_num name_text. type. y_ref. match_byte reference. vary apply_to. labels. show_key. italic. minus include. replace_text. drop. hilo. auto_size. auto_text. criteria_ref. color. start_num. chart_depth. series_line. strike. outline. width layer_num. series_dist. name_text. strike. y_off. italic. add_indent text. vary. gap_width. shadow name_text. size. amount. underline.

xy_series. cell_ref. window_text type_num. format. add_logical add_text. alternate_location. help_file to_recipients. default_location. delete_overlay type_num. description. write_res_pwd. file_access. filter_number chart. drop. fixed. converter document_text1. overlap. editable. hilo. font_name. lock_text file_text. other. tab. text_qualifier. autocomplete. which_address name_text. copy_objects.. decimals. start_row. subject. consecutive_delim. print_object locked.. save_values display_blanks. delete_overlay type_num. icon_label file_name. display_icon_logical. shortcut_on. drag_drop. tips. icon_number. y_secondary. shortcut_key. ignore_rorec. update_links. max_change. y_primary. iter. enclosures.. size_with_window incell_edit. prot_pwd. delete_overlay target_cell. status_bar_text. y_pos. icon_file. sheet_num. y_major. x_primary. file_origin. 2D_effect shift_num object_class. download_logical type_num. enable_under string_array import_ref. help_id. cluster. menu_text. link_logical. dde_on. document_text2. z_minor. update_links. variable_cell x_major. file_type. precision. sum_info. type_of_link subject. date_1904. alert. overlap%. stack. entermove. x_secondary accel_text. password_text. read_only. . cc_recipients. file_origin. by_row def_rtl_sheet. max_num. z_major. x_minor. animations R1C1_mode. menu_on. file_name. link. delete_overlay type_num. accel2_text. target_value. notify_logical. font_size. 3d_shading macro_name. delete_overlay type_num. plot_visible. user_info. angle type_num x_pos. calc_save. y_minor. update. vary. crsr_mvmt. read_only. 100. move_direction. field_info type_num. space. comments file_name. delete_overlay type_num. old_menus. comma. bcc_recipients. add_logical. recent_files. start_char. multi_select. delete_overlay name_text type_num. gui_lang . 3d_shading range.xlDialogGalleryBar xlDialogGalleryColumn xlDialogGalleryCustom xlDialogGalleryDoughnut xlDialogGalleryLine xlDialogGalleryPie xlDialogGalleryRadar xlDialogGalleryScatter xlDialogGoalSeek xlDialogGridlines xlDialogImportTextFile xlDialogInsert xlDialogInsertHyperlink xlDialogInsertNameLabel xlDialogInsertObject xlDialogInsertPicture xlDialogInsertTitle xlDialogLabelProperties xlDialogListboxProperties xlDialogMacroOptions xlDialogMailEditMailer xlDialogMailLogon xlDialogMailNextLetter xlDialogMainChart xlDialogMainChartType xlDialogMenuEditor xlDialogMove xlDialogNew xlDialogNewWebQuery xlDialogNote xlDialogObjectProperties xlDialogObjectProtection xlDialogOpen xlDialogOpenLinks xlDialogOpenMail xlDialogOpenText xlDialogOptionsCalculation xlDialogOptionsChart xlDialogOptionsEdit xlDialogOptionsGeneral xlDialogOptionsListsAdd xlDialogOptionsListsAdd xlDialogOptionsME type_num. drop_size. function_category. semicolon. show_ctrl_char. num_chars placement_type. custom_delimit. other_char.

hlength. periods name. subject. rounded. tmajor. headers. row_grand. draft head. row_dir. apply start. lstyle. vary. source. aauto. replace. lcolor. top. afore. icon_file. lcolor. top. foot_margin. sheet_tabs auto_styles. reserved placement_type range_num. bw_cells. windows. paper_size. newui lauto. gridlines. newfill lauto. lwt. outline. size. printer_text. operation_num. cluster. left. keywords. right. create_apply type_num. quality. objects. auto_page. destination. shadow. color_num. right. apply. mauto. bcolor. newui bauto. head_margin. save_data. scale. apattern. col_grand. series paste_num format_text. auto type_num head. hilo. draft head. vert_scroll. hdng. afore. selection. help_logical. accel_text2 . formulas. left. foot. quality. pg_num parse_text. pg_order. by. mstyle. lwt. shadow. apply_auto_format. mfore. 100. htype bauto. foot_margin. orient. scale. color. object_num. stack. skip_blanks. trans_eval. bcolor. titles. head_margin. col_dir. icon_label apattern. notes. scenarios default_logical. comments contents. bot. paper_size. right. bot. display_icon_logical. lcolor. notes. print_what. overlap. new_name. lcolor. bwt. apattern. orient. invert. copies. pastelink_logical. lstyle. foot. status. lwt. apply. grid. bw_chart. tlabel lauto. orientation. password. overlap%. aback. aback. page_breaks. picture_units. v_cntr. function. accel_text. pivot_field_name. mback. trans_entry formula. quality. zeros. name. icon_number. apply. feed. menu_key_action. dismiss_logical. paper_size. bstyle. aauto.xlDialogOptionsTransition xlDialogOptionsView xlDialogOutline xlDialogOverlay xlDialogOverlayChartType xlDialogPageSetup xlDialogPageSetup xlDialogPageSetup xlDialogParse xlDialogPasteNames xlDialogPasteSpecial xlDialogPasteSpecial xlDialogPasteSpecial xlDialogPasteSpecial xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPatterns xlDialogPhonetic xlDialogPivotCalculatedField xlDialogPivotCalculatedItem xlDialogPivotClientServerSet xlDialogPivotFieldGroup xlDialogPivotFieldProperties xlDialogPivotFieldUngroup xlDialogPivotShowPages xlDialogPivotSolveOrder xlDialogPivotTableOptions xlDialogPivotTableWizard xlDialogPlacement xlDialogPrint xlDialogPrinterSetup xlDialogPrintPreview xlDialogPromote xlDialogProperties xlDialogProtectDocument xlDialogProtectSharing xlDialogPublishAsWebPage xlDialogPushbuttonProperties menu_key. transpose rowcol. page_field type. left. smooth lauto. show_info. v_cntr. h_cntr. quality. h_cntr. angle. hor_scroll. cancel_logical. destination_ref paste_num. tminor. author. head_margin. afore. lstyle. draft. y_resolution. lstyle. formats name. aback. scale. smooth type. pg_num. from. lwt. top. to. orient. bwt. print_to_file. bstyle. bot. end. nav_keys. drop. foot_margin. foot. hwidth. collate printer_text rowcol title. series_num. preview. pg_num. categories.

status.xlDialogReplaceFont xlDialogRoutingSlip xlDialogRowHeight xlDialogRun xlDialogSaveAs xlDialogSaveCopyAs xlDialogSaveNewObject xlDialogSaveWorkbook xlDialogSaveWorkspace xlDialogScale xlDialogScale xlDialogScale xlDialogScale xlDialogScale xlDialogScenarioAdd xlDialogScenarioCells xlDialogScenarioEdit xlDialogScenarioMerge xlDialogScenarioSummary xlDialogScrollbarProperties xlDialogSelectSpecial xlDialogSendMail xlDialogSeriesAxes xlDialogSeriesOptions xlDialogSeriesOrder xlDialogSeriesShape xlDialogSeriesX xlDialogSeriesY xlDialogSetBackgroundPicture xlDialogSetPrintTitles xlDialogSetUpdateStatus xlDialogShowDetail xlDialogShowToolbar xlDialogSize xlDialogSort xlDialogSort xlDialogSortSpecial xlDialogSplit xlDialogStandardFont xlDialogStandardWidth xlDialogStyle xlDialogSubscribeTo xlDialogSubtotalCreate xlDialogSummaryInfo xlDialogTable xlDialogTabOrder font_num. color. major. step document_text. key2. shadow recipients. key2. logarithmic. max cat_labels. window_text orientation. show_field bar_id. replace. width. cross. logarithmic. key3. order1. order. reference. scen_comment. order1. message. size_num. italic. prot_pwd. keywords. case col_split. series_marks. custom sort_by. standard_height. header. key3. strike. levels recipients. hidden source_file result_ref. pagebreaks. italic. new_series_num x_ref name_ref. type. underline. value_array. link. max. size_num. color. height. max_num. color_buttons width. changing_ref. function_num. underline. y_pos. return_receipt axis_num chart_num. major. locked. visible. order3. status_logical height_num. backup. format_num at_change_in. method. between. reverse. header. max. custom. minor. read_only_rec document_text document_text. scen_comment. subject. author. min. cat_marks. key1. key1. reverse min_num. subject. order2. locked. expand. type_num. row_split name_text. shadow standard_num bold. italic file_text. write_res_pwd. value_array. reverse min_num. new_scenname. 3d_shading type_num. backup. reverse. prot_pwd. x_pos. large_buttons. rowcol_num. minor. hidden changing_ref scen_name. reverse. route_num. min scen_name. column_ref . strike. cat_marks. return_logical. between series_labels. type_num reference. cross. tool_tips. bold. bold. report_type value. page. titles_for_rows_ref link_text. write_res_pwd. name_text. order3. type_num. type_of_link rowcol. value_type. read_only_rec name_text cross. outline. key1. total. comments row_ref. subject. y_ref titles_for_cols_ref. case orientation. max_num. protect. order1. order2. summary_below title. changing_ref. outline. cat_labels. inc. dock. old_series_num.

windows. entermove. y_pos. comma. consecutive_delim. The following example displays a form and saves the form data. r1c1. menu_key_action. password ratio_num sheet_text name_array fixed. dest_book. The following example sets the Text property of a text box to "Hello. window_text name_array. bound_logical.xlDialogTextToColumns xlDialogUnhide xlDialogUpdateLink xlDialogVbaInsertFile xlDialogVbaMakeAddIn xlDialogVbaProcedureDefinition xlDialogView3d xlDialogWebOptionsEncoding xlDialogWebOptionsFiles xlDialogWebOptionsFonts xlDialogWebOptionsGeneral xlDialogWebOptionsPictures xlDialogWindowMove xlDialogWindowSize xlDialogWorkbookAdd xlDialogWorkbookCopy xlDialogWorkbookInsert xlDialogWorkbookMove xlDialogWorkbookName xlDialogWorkbookNew xlDialogWorkbookOptions xlDialogWorkbookProtect xlDialogWorkbookTabSplit xlDialogWorkbookUnhide xlDialogWorkgroup xlDialogWorkspace xlDialogZoom destination_ref. status. you can save the information to module-level variables while the form is still running. nav_keys. remote.Text = "Hello" The data entered on a form by a user is lost when the form is closed." TextBox1. height. tab. rotation. type_of_link filename_text elevation. new_name structure. newname_text sheet_name. scroll. semicolon. other. formula. position_num type_num name_array. field_info window_text link_text. ' Code in module to declare public variables. dest_book. you get the initial values for the controls rather than the values the user entered. space. notes. dest_book. other_char. If you want to save the data entered on a form. position_num oldname_text. window_text width. underlines. show_info magnification   Using Control Values While Code Is Running Some control properties can be set and returned while Visual Basic code is running. menu_key. Public strRegion As String Public intSalesPersonID As Integer Public blnCancelled As Boolean . perspective. autoscale x_pos. data_type. height%. position_num name_array. text_delim. decimals. axes. If you return the values of controls on a form after the form has been unloaded. drag_drop. tools.

ListIndex) Module1. click Run Sub/UserForm on the Run menu in the Visual Basic Editor. The following example displays the dialog box named UserForm1. intSalesPersonID = txtSalesPersonID.Show If blnCancelled = True Then MsgBox "Operation Cancelled!".Show End Sub   . Private Sub cmdCancel_Click() Module1.blnCancelled = False Unload Me End Sub Private Sub UserForm_Initialize() Module1.' Code in form. To display a dialog box from Visual Basic. vbExclamation Else MsgBox "The Salesperson's ID is: " & intSalesPersonID & _ "The Region is: " & strRegion End If End Sub   Displaying a Custom Dialog Box To test your dialog box in the Visual Basic Editor.blnCancelled = True End Sub ' Code in module to display form. use the Show method. Sub LaunchSalesPersonForm() frmSalesPeople.Text strRegion = lstRegions.blnCancelled = True Unload Me End Sub Private Sub cmdOK_Click() ' Save data.List(lstRegions. Private Sub GetUserName() UserForm1.

AddItem "East" . The following example uses the AddItem method to add data to a list box. you could fill a list box.Text = "00000" . you must create a new object using the WithEvents keyword in a class module. or when any PivotTable is created or opened.Text = "Default Name" End Sub   Application Object Events Application events occur when a workbook is created or opened.AddItem "North" . End With End Sub You can also use code in the Intialize event of a form to set initial values for controls on the form.AddItem "Test One" UserForm1. An advantage to setting initial control values in the Initialize event is that the initialization code stays with the form.lstNames.lstRegions.lstRegions. To write event procedures for the Application object.lstNames.AddItem "Test Two" UserForm1. Private Sub GetUserName() With UserForm1 . For more information.AddItem "South" ..AddItem "West" . or set option buttons.txtSalesPersonID. when any sheet in any open workbook changes.txtUserName. NewWorkbook SheetActivate SheetBeforeDoubleClick SheetBeforeRightClick SheetCalculate SheetChange SheetDeactivate SheetFollowHyperlink SheetSelectionChange SheetPivotTableUpdate WindowResize WorkbookActivate WorkbookAddinInstall WorkbookAddinUninstall WorkbookBeforeClose WorkbookBeforePrint WorkbookBeforeSave WorkbookDeactivate WorkbookNewSheet WorkbookOpen . set text values. see Using Events with the Application Object. Then it sets the value of a text box and displays the form. For example. and when you run the Show method to display the dialog box.lstRegions.Show ' .. the controls will be initialized. Private Sub UserForm_Initialize() UserForm1. You can copy the form to another project.lstRegions.Initializing Control Properties You can initialize controls at run time by using Visual Basic code in a macro.

your code remains in procedures with the previous name.SeriesCollection(SeriesIndex). open a module by double-clicking the form or control. For example.ColorIndex = 3 End Sub   Control and Dialog Box Events After you have added controls to your dialog box or document. This example changes a point's border color when the user changes the point value. . Event procedures include the name of the control. a command button has a Click event that occurs when the user clicks the command button. _ Points(PointIndex) p. You will need to move code from Command1_Click to Command2_Click. right-click the sheet tab and select View Code from the shortcut menu. Private Sub Chart_SeriesChange(ByVal SeriesIndex As Long. you will not see any code in the Click event procedure. Events on chart sheets are enabled by default.WindowActivate WindowDeactivate WorkbookPivotTableCloseConnection WorkbookPivotTableOpenConnection   Chart Object Events Chart events occur when the user activates or changes a chart. you add event procedures to determine how the controls respond to user actions. For example. _ ByVal PointIndex As Long) Set p = ActiveChart. User forms and controls have a predefined set of events. To view the event procedures for a sheet. you must create a new object using the WithEvents keyword in a class module. If you add code to an event procedure and then change the name of the control.Border. When you double-click Command2. see Using Events with Embedded Charts. assume you add code to the Click event for Commmand1 and then rename the control to Command2. and UserForms have an Initialize event that runs when the form is loaded. Select the event name from the Procedure drop-down list box. and select the event from the Procedure drop-down list box. To write a control or form event procedure. Activate BeforeDoubleClick BeforeRightClick Calculate Deactivate DragOver DragPlot MouseDown MouseMove MouseUp Resize Select SeriesChange Note To write event procedures for an embedded chart. the name of the Click event procedure for a command button named Command1 is Command1_Click. For more information. For example.

_ Cancel As Boolean) For Each icbc In Application.CommandBars("cell").Delete Next icbc If Not Application. or to make a small change to the default behavior. Private Sub Worksheet_Calculate() Columns("A:F").Tag = "brccm" Then icbc.To simplify development.Caption = "New Context Menu Item" .Tag = "brccm" End With End If End Sub   Using Events with Excel Objects .CommandBars("cell"). Private Sub Worksheet_BeforeRightClick(ByVal Target As Range. when the user changes a worksheet cell.OnAction = "MyMacro" .   Worksheet Object Events Events on sheets are enabled by default.Controls If icbc.Controls _ .Add(Type:=msoControlButton. The following example traps the right-click event and adds a new menu item to the shortcut menu for cells B1:B10. Range("b1:b10")) _ Is Nothing Then With Application. The following example adjusts the size of columns A through F whenever the worksheet is recalculated. or when the PivotTable changes. _ temporary:=True) . To view the event procedures for a sheet.AutoFit End Sub Some events can be used to substitute an action for the default application behavior. it is a good practice to name your controls before writing code. before:=6. right-click the sheet tab and click View Code on the shortcut menu.Intersect(Target. Select one of the following events from the Procedure drop-down list box. Activate BeforeDoubleClick BeforeRightClick Calculate Change Deactivate FollowHyperlink PivotTableUpdate SelectionChange Worksheet-level events occur when a worksheet is activated.

Example Application. Finally. The following Sub procedure uses the Min worksheet function to determine the smallest value in a range of cells. you must create a new object using the WithEvents keyword in a class module. Worksheets(1). Sub UseFunction() Dim myRange As Range Set myRange = Worksheets("Sheet1"). For a list of the worksheet functions you can use. Calling a Worksheet Function from Visual Basic In Visual Basic. In a worksheet cell. or Application object. is assigned the result of applying the Min function to myRange. First.Min(myRange) MsgBox answer End Sub If you use a worksheet function that requires a range reference as an argument. answer. Sub FindFirst() myVar = Application.Range("A1:C10") answer = Application.EnableEvents = False ActiveWorkbook. Another variable. and then it is set to range A1:C10 on Sheet1.Range("A1:A10"). the Activate event occurs at the sheet level. QueryTable object.Save Application. chart.You can write event procedures in Microsoft Office Excel at the worksheet. or application level. To write event procedures for an embedded chart. the variable myRange is declared as a Range object. Note Some worksheet functions are not useful in Visual Basic. you would specify a Range object to get the same result. chart sheet. see List of Worksheet Functions Available to Visual Basic. and workbook event procedures are available for any open sheet or workbook. workbook. Worksheet. you can use the Match worksheet function to search a range of cells. the value of answer is displayed in a message box.WorksheetFunction _ . you would enter a formula such as =MATCH(9. using the Save method to save a workbook causes the BeforeSave event to occur. Use the EnableEvents property to enable or disable events. the SheetActivate event occurs when any sheet in any open workbook is activated.WorksheetFunction.Match(9.A1:A10. in a Visual Basic procedure. 0) . You can prevent this by setting the EnableEvents property to False before you call the Save method. the Microsoft Excel worksheet functions are available through the WorksheetFunction object. you must specify a Range object. and the SheetActivate event is available at both the workbook and application levels. At the application level. the Concatenate function is not needed because in Visual Basic you can use the & operator to join multiple text values. query table. However. For example.EnableEvents = True   Using Microsoft Excel Worksheet Functions in Visual Basic You can use most Microsoft Excel worksheet functions in your Visual Basic statements. For example.0). For example. For example. The SheetActivate event for a workbook occurs when any sheet in the workbook is activated.

For example. Static loanAmt Static loanInt Static loanTerm loanAmt = Application.WorksheetFunction. . you specify the function as the value of the Formula property of the corresponding Range object. In the following example.Pmt(loanInt / 1200. loanAmt) MsgBox "Monthly payment is " & Format(payment. Type:=1) loanTerm = Application.InputBox _ (Prompt:="Annual interest rate (8. "Currency")   Working with Shapes (Drawing Objects) Shapes. In general. Type:=1) loanInt = Application. Type:=1) payment = Application. and you use the ShapeRange collection to modify multiple shapes the same way you work with multiple shapes in the user interface.InputBox _ (Prompt:="Term in years (30 for example)". and the Shape object. Application. you use the Shape object to format or modify a single shape. _ Default:=loanTerm.000 for example)". Inserting a Worksheet Function into a Cell To insert a worksheet function into a cell.Range("A1:B3"). the ShapeRange collection. loanTerm * 12. _ Default:=loanAmt. the RAND worksheet function (which generates a random number) is assigned to the Formula property of range A1:B3 on Sheet1 in the active workbook.Log and Log will return different values. or drawing objects. are represented by three different objects: the Shapes collection. _ Default:=loanInt.MsgBox myVar End Sub Note Visual Basic functions do not use the WorksheetFunction qualifier. Sub InsertFormula() Worksheets("Sheet1"). A function may have the same name as a Microsoft Excel function and yet work differently. Notice that this example uses the InputBox method instead of the InputBox function so that the method can perform type checking. you use the Shapes collection to create shapes and to iterate through all the shapes on a given worksheet.InputBox _ (Prompt:="Loan amount (100.WorksheetFunction _ . these are displayed as default values the next time you run the program.Formula = "=RAND()" End Sub Example This example uses the worksheet function Pmt to calculate a home mortgage loan payment. The Static statements cause Visual Basic to retain the values of the three variables.75 for example)".

and then you set the ForeColor property of the FillFormat object to set the fill foreground color for the specified shape.Fill. If the operation does not work on multiple selected shapes in the user interface.ForeColor. To set properties for a shape. you can perform the same operation in Visual Basic by constructing a ShapeRange collection that contains the shapes you want to work with. For example. which contains all the properties that relate to the shape's fill. Worksheets(1). the Index argument is not optional for the Range property of the Shapes collection. 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. You can perform other operations with only a single shape selected. The following example constructs a shape range that contains the shapes named "Big Star" and "Little Star" on myDocument and applies a gradient fill to them.Shapes(1). _ . Worksheets(1). you can edit the text in a shape only if a single shape is selected. Applying a Property or Method to a ShapeRange Collection If you can perform an operation on multiple selected shapes in the user interface at the same time. or the LinkFormat object. so you cannot use this property without an argument to create a ShapeRange object containing all shapes in a Shapes collection. In Visual Basic. you can select several shapes and set all their individual fills at once. 0. related shape attributes are grouped under secondary objects. the TextFrame property fails if applied to a shape that cannot contain text.Range(Array("Big Star". Instead. you use the Fill property to return the FillFormat object. you must first return the object that represents the set of related shape attributes and then set properties of that returned object. 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. as shown in the following example. and applying the appropriate properties and methods directly to the ShapeRange collection. which contains all the properties that are unique to linked OLE objects. there are two ways to apply properties and methods to a set of shapes. Creating a ShapeRange Collection that Contains All Shapes on a Sheet You can create a ShapeRange object that contains all the Shape objects on a sheet by selecting the shapes and then using the ShapeRange property to return a ShapeRange object containing the selected shapes.ShapeRange In Microsoft Excel. For example. If you are not positive that each of the shapes in a ShapeRange collection can have a certain property or method applied to it. for example. you can perform some operations with several shapes selected. These two ways allow you to perform any operation that you can perform on a single shape on a range of shapes. 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.Shapes.RGB = RGB(255. 0) Applying a Property or Method to Several Shapes at the Same Time In the user interface.Select Set sr = Selection.Shapes. If you want to apply one of these properties or methods to a collection of shapes.Setting Properties for a Shape Many formatting properties of shapes are not set by properties that apply directly to the Shape or ShapeRange object. Many properties and methods that apply to the Shape object and ShapeRange collection fail if applied to certain kinds of shapes. you can do the programmatic equivalent by constructing a ShapeRange collection and then applying the appropriate properties or methods to it. do not apply the property or method to the ShapeRange collection. and applying the appropriate properties and methods to the individual Shape objects in the collection. Set myDocument = Worksheets(1) Set myRange = myDocument. for example. such as the FillFormat object.

For Each sh in ActiveWindow.Fill. If the collection contains more than one shape. it returns the "mixed" constant.Type = msoAutoShape Then sh.ForeColor.PresetGradient _ msoGradientHorizontal. you will be able to return the object from a ShapeRange collection and set its properties. and Grouping Shapes in a Shape Range Use the Align and Distribute methods to position a set of shapes relative to one another or relative to the document that contains them. If the secondary object represents operations that can be performed on multiple selected objects in the user interface.Shapes If sh. 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 simple data type (such as Long. 0. Single. 1. Applying a method to the collection is equivalent to applying the method to each individual Shape object in that collection. Distributing. you can perform the equivalent action programmatically by looping through a Shapes or ShapeRange collection that contains the shapes you want to work with.RGB = RGB(255. 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).Fill. applying the appropriate properties and methods to the individual Shape objects in the collection. 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. you can use the Fill property to return the FillFormat object that represents the fills of all the shapes in the ShapeRange collection. . For example. 0) End If Next 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. a run-time error occurs. such as the FillFormat object. 0. Set myDocument = Worksheets(1) For Each sh In myDocument. The value of some properties can be returned or set only if there is exactly one shape in the collection.ForeColor. msoGradientBrass The following are general guidelines for how properties and methods behave when they are applied to a ShapeRange collection. Looping Through a Shapes or ShapeRange Collection Even if you cannot perform an operation on several shapes in the user interface at the same time by selecting them and then using a command.RGB = RGB(255."Little Star")) myRange. If not all shapes in the collection have the same value for the property. The following example loops through all the shapes on myDocument and changes the foreground color for each AutoShape shape.ShapeRange sh. 0) Next Aligning. Setting the properties of this FillFormat object will set the same properties for all the individual shapes in the ShapeRange collection.Selection. The preceding guidelines also apply when you are setting properties of shapes that are grouped under secondary objects of the ShapeRange collection. 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. Use the Group method or the Regroup method to form a single grouped shape from a set of shapes.Fill.

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 . For more information on a particular function.List of Worksheet Functions Available to Visual Basic The following list represents all of the worksheet functions that can be called using the WorkSheetFunction object. see the Function Reference topic on Microsoft Office Online.

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 .

you must create a new class module and declare an object of type Chart with events. and the event procedures in the class module will run when the events occur. the myChartClass object in the class module points to embedded chart 1 on worksheet 1. The new class module contains the following code: Public WithEvents App As Application After the new object has been declared with events. The new class module contains the following code.ChartObjects(1). Using Events with the Application Object Before you can use events with the Application object. assume that a new class module is created and called EventClassModule. you must create a class module and declare an object of type Application with events.) Before the procedures will run. You can do this by using the following code from any module. and you can write event procedures for the new object. assume that a new class module is created and named EventClassModule.ZTest   Using Events with Embedded Charts Events are enabled for chart sheets by default. the valid events for that object are listed in the Procedure drop-down list box. Dim myClassModule As New EventClassModule Sub InitializeChart() Set myClassModule. it appears in the Object drop-down list box in the class module.myChartClass = _ Charts(1).App = Application End Sub . you must connect the declared object in the class module with the Application object. (When you select the new object in the Object box. it appears in the Object drop-down list box in the class module. You can do this with the following code from any module. however. you must connect the declared object in the class module with the embedded chart.Chart End Sub After you run the InitializeChart procedure. Before you can use events with a Chart object that represents an embedded chart. and you can write event procedures for this object. Example Dim X As New EventClassModule Sub InitializeApp() Set X. (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. For example. For example.) Before your procedures will run. however. Public WithEvents myChartClass As Chart After the new object has been declared with events.

wbXL As Excel. .InitQueryEvent _ QT:=ActiveSheet. Before the procedures will run. Using Events with the QueryTable Object Before you can use events with the QueryTable object. the App object in the class module points to the Microsoft Excel Application object. After you have done this.After you run the InitializeApp procedure. it appears in the Object drop-down list box in the class module. In this example. This module contains the following code: Public WithEvents qtQueryTable As QueryTable After you have declared the new object by using events.Workbook Note You must follow the preceding steps if you want your code to be early bound.   Controlling One Microsoft Office Application from Another If you want to run code in one Microsoft Office application that works with the objects in another application. the first query table on the active worksheet is connected to the qtQueryTable object. follow these steps. When you click the new object in the Object box. you must connect the declared object in the class module to the specified QueryTable object. 1. You can initialize the event in a module by calling the event. Dim clsQueryTable as New ClsModQT Sub RunInitQTEvent clsQueryTable. however. You can do this by entering the following code in the class module: Sub InitQueryEvent(QT as Object) Set qtQueryTable = QT End Sub After you run this initialization procedure. the valid events for that object are displayed in the Procedure drop-down list box. Declare object variables that will refer to the objects in the other application as specific types. For example. You can also get context-sensitive Help on them.Application. assume that you have created a class module and named it ClsModQT. the objects. For example. and the event procedures in the class module will run when the events occur. 2. properties. Set a reference to the other application's type library in the References dialog box (Tools menu). the object you declared in the class module points to the specified QueryTable object.QueryTables(1) End Sub You can write other event procedures in the object's class. and methods will show up in the Object Browser and the syntax will be checked at compile time. you must first create a class module and declare a QueryTable object with events. Make sure you qualify each type with the name of the application that is supplying the object. the following statement declares a variable that points to a Microsoft Word document and another that refers to a Microsoft Excel workbook: Dim appWD As Word.

as shown in the following example.Application Set appWD = CreateObject("Word. Dim appWD As Word. The following example builds a dynamic data set and applies color to the above average values through conditional formatting rules. Apply properties and methods to the object contained in the variable.Quit   Excel Developer Reference AboveAverage Object Represents an above average visual of a conditional formatting rule.Value = "Kelli-1" .Application Set appWD = CreateObject("Word. use the Quit method to close it. Dim appWD As Word.Value = "Name" Range("B1"). If you want to see the session of the other application.Visible = True 4. as shown in the following example. For example. Version Information Remarks Version Added: Excel 2007 All conditional formatting objects are contained within a FormatConditions collection object. You can create an above average formatting rule by using either the Add or AddAboveAverage method of the FormatConditions collection. Visual Basic for Applications Example Sub AboveAverageCF() ' Building data for Kelli Range("A1").Value = "Number" Range("A2"). which is a child of a Range collection. Applying a color or fill to a range or selection to help you see the value of a cells relative to other cells. the following instruction creates a new Word document.Application") appWD.Add 5.3. When you are done working with the other application. appWd. Use the CreateObject function with the OLE Programmatic Identifiers of the object you want to work with in the other application. set the Visible property to True.Documents.Application") appWd.

Range("A2"). vbInformation Press F9 to update End Sub   AboveAverage Object Members Methods Name Delete ModifyAppliesToRange SetFirstPriority SetLastPriority Description Deletes the specified conditional formatting rule object. Read-only.Font .FormulaArray = "=INT(RAND()*101)" Range("B2:B26"). Properties Name AboveBelow Description 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.Count).PatternColorIndex = xlAutomatic .AboveBelow = xlAboveAverage With Selection. Sets the priority value for this conditional formatting rule to "1" so that it will be evaluated before all other rules on the worksheet. Sets the evaluation order for this conditional formatting rule so it is evaluated after all other rules on the worksheet.FormatConditions(1).Color = -16752384 .FormatConditions(Selection. values.Interior . When used without an object qualifier. this property returns an Application object that represents the Microsoft Office Excel application. Type:=xlFillDefault Range("B2:B26").FormatConditions. Returns a Borders collection that specifies the formatting of cell borders if the conditional formatting Application AppliesTo Borders .TintAndShade = 0 End With With Selection.Color = 13561798 . Selection.SetFirstPriority Selection.TintAndShade = 0 End With MsgBox "Added an Above Average Conditional Format to Kelli's data.FormatConditions(1). When used with an object qualifier.". this property returns an Application object that represents the creator of the specified object.AddAboveAverage Should appear green Selection. Returns a Range object specifying the cell range to which the formatting rule is applied.AutoFill Destination:=Range("A2:A26"). Sets the cell range to which this formatting rule applies.FormatConditions(1).FormatConditions.Select ' Applying Conditional Formatting to items above the average. fill and dark green font.

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. Returns one of the constants of the XlFormatConditionType enumeration. Read-only. Returns or sets one of the constants of the XlPivotConditionScope enumeration. Read-only. CalcFor Font FormatRow Interior NumberFormat Parent Priority PTCondition ScopeType StopIfTrue Type Returns or sets one of the constants of XlCalcFor enumeration which specifies the scope of data to be evaluated for the conditional format in a PivotTable report. Returns an Interior object that specifies a cell's interior attributes for a conditional formatting rule that evaluates to True.Application Version Added: Excel 2007 expression A variable that represents an AboveAverage object. which specifies the type of conditional format. When used with an object qualifier. this property returns an Application object that represents the creator of the specified object. this property returns an Application object that represents the Microsoft Office Excel application.rule evaluates to True. Returns or sets the priority value of the conditional formatting rule. Returns or sets a Boolean value that determines if additional formatting rules on the cell should be evaluated if the current rule evaluates to True.Application Property When used without an object qualifier. Returns or sets the number format applied to a cell if the conditional formatting rule evaluates to True. The priority determines the order of evaluation when multiple conditional formatting rules exist in a worksheet. Read-only. Returns a Boolean value indicating if the conditional format is being applied to a PivotTable chart. Returns the parent object for the specified object. Read-only. Read-only. AboveAverage.AboveBelow Version Added: Excel 2007 expression A variable that represents an AboveAverage object. Returns or sets a Boolean value specifying if the entire Excel table row should be formatted if the conditional format rule evaluates to True. Version Information Syntax expression. specifying if the conditional formatting rule looks for cell values above or below the range average or standard deviation. Version Information Syntax expression. Read/write Variant. which determines the scope of the conditional format when it is applied to a PivotTable chart. Read-only. either installed or not installed. Remarks . Read-only.   Excel Developer Reference AboveAverage. Returns a Font object that specifies the font formatting if the conditional formatting rule evaluates to True. The default value is False.AboveBelow Property Returns or sets one of the constants of the XlAboveBelow enumeration.

which is the file name of the add-in. "Full Name". you must first use the Add method and then set the Installed property. 2) = AddIns(i).Range("a1"). where index is the add-in title or index number.xla") The following example sets the wb variable to the workbook for the Analysis Toolpak add-in. Visual Basic for Applications AddIns. "Installed") For i = 1 To AddIns.xll"). with the Add method). The following example creates a list that contains specified properties of the available add-ins. Visual Basic for Applications Set wb = Workbooks("myaddin. regardless of whether they’re installed. not its title. to return a single AddIn object. This example sets the wb variable to the workbook for Myaddin.Cells(i + 1.Cells(i + 1. You must spell the add-in title exactly as it’s spelled in the Add-Ins dialog box. This can be done in a single step.Bold = True . with the add-in name.Add("generic.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. Example Use AddIns(index).Font. Set the Installed property of the add-in to True to install the add-in. The index number represents the position of the add-in in the Add-ins available box in the Add-Ins dialog box. The AddIns collection contains a list of all the add-ins available to Microsoft Excel. which appears in the Add-Ins dialog box. 3) = AddIns(i).Installed Next . "Title". This list corresponds to the list of add-ins displayed in the AddIns dialog box.FullName .Cells(i + 1.xla.The AddIn object is a member of the AddIns collection. To install an add-in that doesn’t appear in the list of available add-ins. Visual Basic for Applications With Worksheets("sheet1") .Columns. 4) = AddIns(i).CurrentRegion.Count .Name .AutoFit End With The Add method adds an add-in to the list of available add-ins but doesn’t install the add-in.Range("a1:d1"). .Installed = True Don’t confuse the add-in title. as shown in the following example (note that you use the name of the add-in. 1) = AddIns(i).Value = _ Array("Name". but the capitalization doesn’t have to match. You must use the file name because loaded add-ins don’t normally appear in the Workbooks collection. The following example installs the Analysis Toolpak add-in.Rows(1). Visual Basic for Applications AddIns("analysis toolpak").Cells(i + 1.Title .

Application.Name) If the Installed property returns True. identifying an object. Set wbMyAddin = Workbooks. but calls to functions in the add-in still fail. 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). or CLSID.FullName) End If ' restore error checking   AddIn. Manually open it." Else MsgBox "This is not an Excel Application object. Visual Basic for Applications On Error Resume Next ' turn off error checking Set wbMyAddin = Workbooks(AddIns("My Addin"). this property returns an Application object that represents the Microsoft Excel application. Read-only.CLSID Property Returns a read-only unique identifier.Visual Basic for Applications Set wb = Workbooks(AddIns("analysis toolpak"). Syntax .Open(AddIns("My Addin"). Syntax expression. you should open the add-in workbook. When used with an object qualifier. as a String." End If   AddIn.Value = "Microsoft Excel" Then MsgBox "This is an Excel Application object. Visual Basic for Applications Set myObject = ActiveWorkbook If myObject.Application Property When used without an object qualifier. Example This example displays a message about the application that created myObject. 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.Name) lastError = Err On Error Goto 0 If lastError <> 0 Then ' the add-in workbook isn't currently open. 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. the add-in may not actually be loaded.Application expression A variable that represents an AddIn object.

Creator expression An expression that returns a AddIn object. Visual Basic for Applications Sub FindCLSID() MsgBox Application. Read-only Long.AddIns("Analysis ToolPak").CLSID expression A variable that represents an AddIn object. .CLSID End Sub AddIn. This example assumes the "Analysis ToolPak" has been installed.FullName Property Returns the name of the object.FullName expression A variable that represents an AddIn object. Example This example returns the CLSID of an add-in titled "Analysis ToolPak".Installed Property True if the add-in is installed. this property returns the string XCEL.FullName Next a   AddIn. where each application has a four-character creator code. Syntax expression. Syntax expression. The Creator property is designed to be used in Microsoft Excel for the Macintosh. which is equivalent to the hexadecimal number 5843454C.expression. For example. Return Value XlCreator Remarks If the object was created in Microsoft Excel. Visual Basic for Applications For Each a In AddIns MsgBox a.   AddIn. including its path on disk. Example This example displays the path and file name of every available add-in. as a string. Microsoft Excel has the creator code XCEL. Read-only String. Read/write Boolean.Creator Property Returns a 32-bit integer that indicates the application in which this object was created.

Name expression A variable that represents an AddIn object. AddIn.Installed expression A variable that represents an AddIn object. Syntax expression. Setting this property to False removes the add-in and calls its Auto_Remove functions.Parent Property Returns the parent object for the specified object.Path expression A variable that represents an AddIn object.Installed = True Then MsgBox "The Solver add-in is installed" Else MsgBox "The Solver add-in is not installed" End If   AddIn.progID Property Returns the programmatic identifiers for the object. Syntax expression. Visual Basic for Applications Set a = AddIns("Solver Add-In") If a. Read-only String. Read-only. AddIn. AddIn.Name Property Returns a String value that represents the name of the object.Syntax expression. Syntax expression. Remarks Setting this property to True installs the add-in and calls its Auto_Add functions. Syntax expression.Parent expression A variable that represents an AddIn object. .progID expression A variable that represents an AddIn object.Path Property Returns a String value that represents the complete path to the application. Example This example uses a message box to display the installation status of the Solver add-in. excluding the final separator and name of the application.

Set the Installed property of the add-in to True to install the add-in. with the Add method). Visual Basic for Applications AddIns.Name Worksheets("Sheet1").ProgId End With Next   AddIns Collection A collection of AddIn objects that represents all the add-ins available to Microsoft Excel.Activate rw = 1 For Each ad In Application.AddIns Worksheets("Sheet1").OLEObjects With Worksheets(2) rw = rw + 1 .Cells(rw. as shown in the following example (note that you use the name of the add-in. 1).Value = o.Cells(rw.Add("generic. not its title. Example Use the AddIns property to return the AddIns collection. Visual Basic for Applications rw = 0 For Each o in Worksheets(1). This can be done in a single step.Installed rw = rw + 1 Next End Sub Use the Add method to add an add-in to the list of available add-ins. 2) = ad. The following example creates a list that contains the names and installed states of all the available add-ins. Remarks This list corresponds to the list of add-ins displayed in the Add-Ins dialog box. The following example installs the Analysis Toolpak add-in.cells(rw. 1) = ad. Visual Basic for Applications Sub DisplayAddIns() Worksheets("Sheet1"). 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.Example This example creates a list of the programmatic identifiers for the OLE objects on worksheet one. regardless of whether they’re installed. The Add method adds an add-in to the list but doesn’t install the add-in.Installed = True Use AddIns(index) where index is the add-in title or index number to return a single AddIn object. .xll").

this property returns an Application object that represents the Microsoft Excel application. which appears in the Add-Ins dialog box. 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)." Else MsgBox "This is not an Excel Application object. with the add-in name. Parameters Name Required/Optional Required Data Type Variant Description The name or index number of the object. Index Example This example displays the status of the Analysis ToolPak add-in." End If AddIns.Don’t confuse the add-in title. Example This example displays a message about the application that created myObject.Application Property When used without an object qualifier. Visual Basic for Applications AddIns("analysis toolpak"). Syntax expression.Installed = True AddIns. Visual Basic for Applications If AddIns. You must spell the add-in title exactly as it’s spelled in the Add-Ins dialog box.Installed = True Then MsgBox "Analysis ToolPak add-in is installed" Else . Visual Basic for Applications Set myObject = ActiveWorkbook If myObject.Value = "Microsoft Excel" Then MsgBox "This is an Excel Application object.Item Property Returns a single object from a collection. which is the file name of the add-in. Read-only. Syntax expression. but the capitalization doesn’t have to match.Item("Analysis ToolPak").Application expression A variable that represents an AddIns object.Application. Note that the string used as the index to the AddIns method is the Title property of the AddIn object. When used with an object qualifier.Item(Index) expression A variable that represents an AddIns object.

to return a single adjustment value. _ CopyFile:=True) MsgBox myAddIn. When you run this example. If this argument is omitted.Add(Filename:="A:\MYADDIN. and different kinds of adjustments have different ranges of valid values.MsgBox "Analysis ToolPak add-in is not installed" End If AddIns. where index is the adjustment value’s index number. the following .xla from drive A. This method does not install the new add-in.XLA". Syntax expression. Filename CopyFile Optional Variant Return Value Remarks An AddIn object that represents the new add-in.Add(FileName. Microsoft Excel copies the file A:\Myaddin. Remarks Each adjustment value represents one way an adjustment handle can be adjusted. Microsoft Excel displays a dialog box and asks you to choose. A shape can have up to eight adjustments. different kinds of adjustments change the geometry of a shape in different ways.Add Method Adds a new add-in file to the list of add-ins.Title & " has been added to the list" End Sub   Adjustments Object Contains a collection of adjustment values for the specified AutoShape. Use the Adjustments property to return an Adjustments object. For example. Returns an AddIn object. Use Adjustments(index). 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). Example This example inserts the add-in Myaddin. CopyFile) expression A variable that represents an AddIns object. You must set the Installed property to install the add-in. WordArt object. Because some adjustment handles can be adjusted in two ways — for instance. Different shapes have different numbers of adjustment values.xla to the Library folder on your hard disk and adds the add-in title to the list in the Add-Ins dialog box. Ignored if the add-in file is on a hard disk. Parameters Name Required/Optional Required Data Type String Description The name of the file that contains the add-in you want to add to the list in the add-in manager. Visual Basic for Applications Sub UseAddIn() Set myAddIn = AddIns. False to have the add-in remain on the removable medium. some handles can be adjusted both horizontally and vertically — a shape can have more adjustment values than it has adjustment handles. or connector.

5 .8 . For example. 10.Item(4) = 0.Application Property . it will be normalized to be within that range.Item(3) = 0. 190) With rac. In most cases. Note Because each adjustable shape has a different set of adjustments.0 are valid values.15 .0 corresponds to the width of the shape. Values are expressed in degrees.0 represents the right or bottom edge of the shape. it has four adjustments. Valid values correspond to valid adjustments you can make to the shape manually.Item(1) = 0. The following table summarizes the ranges of valid adjustment values for different types of adjustments.Shapes. the maximum value for the corresponding adjustment will be 0. Adjustments three and four both correspond to the handle between the head and neck of the arrow. negative numbers and numbers greater than 1. make adjustments with the macro recorder turned on. the closest valid value will be assigned to the adjustment. the best way to verify the adjustment behavior for a specific shape is to manually create an instance of the shape.5. where the values 0. if you specify a value that’s beyond the range of valid values.0 represents the left or top edge of the shape and the value 1. if you can only pull an adjustment handle half way across the shape manually.Item(2) = 0. The maximum value is 0. An adjustment value of 1. Type of adjustment Valid values Generally the value 0.0 represent the limits of the rectangle defined by the starting and ending points of the connector or callout line. _ 10.Adjustments . Visual Basic for Applications Set myDocument = Worksheets(1) Set rac = myDocument. 250. or half way across the shape. For shapes such as connectors and callouts.4 End With 'adjusts width of text box 'adjusts width of arrow head 'adjusts length of arrow head 'adjusts width of arrow neck   Adjustments. Note that although the shape has only three adjustment handles. and then examine the recorded code.AddShape(msoShapeRightArrowCallout.illustration shows what each of the four adjustment values for a right-arrow callout contributes to the definition of the callout’s geometry.5.0 and 1. If you specify a value outside the range – 180 to 180. Linear (horizontal or vertical) Radial Angle Example The following example adds a right-arrow callout to myDocument and sets adjustment values for the callout.

Application. Example In this example.When used without an object qualifier.AllowEditRanges.Application expression A variable that represents an Adjustments object. Read-only.Value = "Microsoft Excel" Then MsgBox "This is an Excel Application object. you can use the ChangePassword method to change the password to access a range that can be edited on a protected worksheet. Example This example displays a message about the application that created myObject." End If   AllowEditRange Object Represents the cells that can be edited on a protected worksheet. then changes the password for this specified range and notifies the user of this change. notifies the user. Visual Basic for Applications Set myObject = ActiveWorkbook If myObject. Once an AllowEditRange object has been returned.Add _ .Protection. When used with an object qualifier. this property returns an Application object that represents the Microsoft Excel application. Syntax expression." Else MsgBox "This is not an Excel Application object. Visual Basic for Applications Sub UseChangePassword() Dim wksOne As Worksheet Dim wksPassword As String Set wksOne = Application. Microsoft Excel allows edits to range "A1:A4" on the active worksheet. wksOne.ActiveSheet wksPassword = InputBox ("Enter password for the worksheet") ' Establish a range that can allow edits ' on the protected worksheet. Remarks Use the Add method or the Item property of the AllowEditRanges collection to return an AllowEditRange object. 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).

ChangePassword _ Password:=wksPassword MsgBox "The password for these cells has been changed.Name End Sub   AllowEditRange. _ Password:=wksPassword MsgBox "Cells A1 to A4 can be edited on the protected worksheet. Syntax . Example In this example.ChangePassword Method Changes the password for a range that can be edited on a protected 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.Title:="Classified". Microsoft Excel displays the name of the first user allowed access to the first protected range on the active worksheet.Users(1).AllowEditRanges(1). MsgBox wksSheet.Protection. wksPassword = InputBox ("Enter the new password for the worksheet") wksOne. Visual Basic for Applications Sub DisplayUserName() Dim wksSheet As Worksheet Set wksSheet = Application. _ Range:=Range("A1:A4").Protection.ActiveSheet ' Display name of user with access to protected range.Users expression A variable that represents an AllowEditRange object.Users Property Returns a UserAccessList object for the protected range on a worksheet.AllowEditRanges(1)." ' Change the password. Syntax expression." End Sub AllowEditRange.

" End Sub AllowEditRanges Collection A collection of all the AllowEditRange objects that represent the cells that can be edited on a protected worksheet. wksOne. The worksheet must be unprotected before running this code. .expression. notifies the user. changes the password for this specified range.ActiveSheet ' Establish a range that can allow edits ' on the protected worksheet. Visual Basic for Applications Sub UseChangePassword() Dim wksOne As Worksheet Dim strPassword As String Set wksOne = Application. Microsoft Excel allows edits to range "A1:A4" on the active worksheet. strPassword = InputBox("Please enter the password for the range") wksOne.AllowEditRanges("Classified"). Password Example In this example.AllowEditRanges.Protection.Protection. Parameters Name Required/Optional Required Data Type String Description The new password. _ Password:=strPassword strPassword = InputBox("Please enter the new password for the range") ' Change the password. Remarks Use the AllowEditRanges property of the Protection object to return an AllowEditRanges collection.Add _ Title:="Classified". _ Range:=Range("A1:A4"). and notifies the user of the change.ChangePassword(Password) expression A variable that represents an AllowEditRange object.ChangePassword _ Password:="strPassword" MsgBox "The password for these cells has been changed.

Once an AllowEditRanges collection has been returned.Item(Index) expression A variable that represents an AllowEditRanges object.Protection.AllowEditRanges.Add _ Title:="Classified".ActiveSheet ' Unprotect worksheet. you can use the Add method to add a range that can be edited on a protected worksheet. Example In this example. Visual Basic for Applications Sub UseAllowEditRanges() Dim wksOne As Worksheet Dim wksPassword As String Set wksOne = Application. _ Password:=wksPassword ' Notify the user ' the title and address of the range.Unprotect wksPassword = InputBox ("Enter password for the worksheet") ' Establish a range that can allow edits ' on the protected worksheet.Title MsgBox "Address of range: " & . wksOne. 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. wksOne. With wksOne.Protection.Item Property Returns a single object from a collection.Item(1) MsgBox "Title of range: " & . _ Range:=Range("A1:A4").Address End With End Sub   AllowEditRanges.Range.AllowEditRanges. Parameters . Syntax expression.

" End Sub Application Object Represents the entire Microsoft Excel application. The following example applies the Windows property to the Application object.AllowEditRanges. such as ActiveCell. Example Use the Application property to return the Application object.Item(1). Visual Basic for Applications . _ Range:=Range("A1:A4").Add _ Title:="Classified". Remarks The Application object contains: Application-wide settings and options. Visual Basic for Applications Sub UseChangePassword() Dim wksOne As Worksheet Set wksOne = Application.AllowEditRanges. ActiveSheet. notifies the user." ' Change the password.Name Required/Optional Required Data Type Variant Description The name or index number of the object. Methods that return top-level objects. then changes the password for this specified range and notifies the user of this change. _ Password:="secret" MsgBox "Cells A1 to A4 can be edited on the protected worksheet.Protection.ChangePassword _ Password:="moresecret" MsgBox "The password for these cells has been changed. wksOne. wksOne. Index Example This example allows edits to range ("A1:A4") on the active worksheet.Protection.ActiveSheet ' Establish a range that can allow edits ' on the protected worksheet. and so on.

this property returns the active cell in the active window. Visual Basic for Applications Set xl = CreateObject("Excel. Visual Basic for Applications Worksheets("Sheet1"). but only one is the active cell. Remarks If you don't specify an object qualifier. For example. Read-only.Bold = True You can write Visual Basic for Applications ActiveCell. such as the active cell (ActiveCell property). and are all equivalent. Because the ActiveCell property fails if the active sheet isn't a worksheet. The selection may contain more than one cell.ActiveWindow.Sheet") xl.Bold = True   Application. If the window isn't displaying a worksheet.xls").Application.Open "newbook. The active cell is a single cell inside the current selection. The following expressions all return the active cell.Activate .ActiveCell Application. this property fails.Activate The following example creates a Microsoft Excel workbook object in another application and then opens a workbook in Microsoft Excel. Be careful to distinguish between the active cell and the selection.ActiveCell expression A variable that represents an Application object.Font.Workbooks. ActiveCell Application. can be used without the Application object qualifier.Application.ActiveCell ActiveWindow. the example activates Sheet1 before using the ActiveCell property.ActiveCell Example This example uses a message box to display the value in the active cell.ActiveCell.Font.Windows("book1.ActiveCell Property Returns a Range object that represents the active cell in the active window (the window on top) or in the specified window. instead of writing Visual Basic for Applications Application. Syntax expression.xls" Many of the properties and methods that return the most common user-interface objects.

HasLegend = True   Application. Remarks If you don't specify an object qualifier. this property returns the active chart in the active workbook.ActivePrinter Property Returns or sets the name of the active printer.ActivePrinter Application.ActivePrinter expression A variable that represents an Application object.MsgBox ActiveCell.ActiveChart Property Returns a Chart object that represents the active chart (either an embedded chart or a chart sheet).Font . Visual Basic for Applications Worksheets("Sheet1"). Example This example displays the name of the active printer. this property returns Nothing.Activate With ActiveCell. Read/write String.Italic = True End With   Application. Syntax expression. Visual Basic for Applications MsgBox "The name of the active printer is " & _ Application. Example This example turns on the legend for the active chart. Returns Nothing if no sheet is active. When no chart is active. Visual Basic for Applications ActiveChart.Bold = True . Syntax expression. .Value This example changes the font formatting for the active cell.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.ActiveChart expression A variable that represents an Application object. An embedded chart is considered active when it's either selected or activated.

Visual Basic for Applications MsgBox "The name of the active sheet is " & ActiveSheet. Remarks . Visual Basic for Applications MsgBox "The name of the active workbook is " & ActiveWorkbook.ActiveWindow expression A variable that represents an Application object. Example This example displays the name of the active workbook.Name Application. Returns Nothing if there are no windows open. Example This example displays the name (Caption property) of the active window. Remarks If you don’t specify an object qualifier. If a workbook appears in more than one window. Syntax expression. the ActiveSheet property may be different in different windows.Caption Application.ActiveSheet expression A variable that represents an Application object. Read-only.ActiveWorkbook Property Returns a Workbook object that represents the workbook in the active window (the window on top).Na Application.ActiveWorkbook expression A variable that represents an Application object.ActiveWindow Property Returns a Window object that represents the active window (the window on top). Example This example displays the name of the active sheet. Read-only. Syntax expression. this property returns the active sheet in the active workbook. Returns Nothing if there are no windows open or if either the Info window or the Clipboard window is the active window.Syntax expression. Syntax expression.AddIns expression A variable that represents an Application object. Visual Basic for Applications MsgBox "The name of the active window is " & ActiveWindow. Read-only.AddIns Property Returns an AddIns collection that represents all the add-ins listed in the Add-Ins dialog box (Tools menu).

not the add-in’s file name.Assistant Property Returns an Assistant object for Microsoft Excel. Example This example displays the status of the Analysis ToolPak add-in. Visual Basic for Applications Application. Syntax expression. Note that the string used as the index to the AddIns collection is the title of the add-in. . Visual Basic for Applications If AddIns("Analysis ToolPak"). Read-only. this property returns an Application object that represents the Microsoft Excel application. 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).Application.Value = "Microsoft Excel" Then MsgBox "This is an Excel Application object. Visual Basic for Applications Set myObject = ActiveWorkbook If myObject.AltStartupPath = "C:\EXCEL\MACROS" Application.AltStartupPath Property Returns or sets the name of the alternate startup folder.Using this method without an object qualifier is equivalent to Application.Application expression A variable that represents an Application object. Example This example displays a message about the application that created myObject. When used with an object qualifier. Syntax expression.Application Property When used without an object qualifier." Else MsgBox "This is not an Excel Application object." End If Application.Addins. Read/write String. Example This example sets the alternate startup folder.AltStartupPath expression A variable that represents an Application object.Installed = True Then MsgBox "Analysis ToolPak add-in is installed" Else MsgBox "Analysis ToolPak add-in is not installed" End If Application.

Syntax expression.AutoCorrect Property Returns an AutoCorrect object that represents the Microsoft Excel AutoCorrect attributes. Visual Basic for Applications Assistant." for the word "Temperature" in the array of AutoCorrect replacements. Read-only.Assistant.AutoFormatAsYouTypeReplaceHyperlinks expression A variable that represents an Application object.AutoCorrect . Example This example makes the Office Assistant visible.AddReplacement "Temperature". "Temp.Visible = True Application. Syntax expression. Remarks Using this property without an object qualifier is equivalent to using Application. Microsoft Excel determines if the ability to format hyperlinks automatically as they are typed is enabled and notifies the user." End With Application. Visual Basic for Applications Sub CheckHyperlinks() ' Determine if automatic formatting is enabled and notify user. Visual Basic for Applications With Application. Read/write Boolean. Syntax expression. Example In this example. Example This example substitutes the word "Temp.AutoCorrect expression A variable that represents an Application object.Assistant expression A variable that represents an Application object.AutoFormatAsYouTypeReplaceHyperlinks Property True (default) if Microsoft Excel automatically formats hyperlinks as you type. False if Excel does not automatically format hyperlinks as you type.AutoFormatAsYouTypeReplaceHyperlinks = True Then MsgBox "Automatic formatting for typing in hyperlinks is enabled." Else . If Application.

This is the default value when the application is started. Uses the security setting specified in the Security dialog box. Enables all macros. Note This setting does not disable Microsoft Excel 4. msoAutomationSecurityByUI. For example. Read/write. Remarks This property is automatically set to msoAutomationSecurityLow when the application is started. to avoid breaking solutions that rely on the default setting. msoAutomationSecurityLow.0 macros. while still showing the security warning if the file open succeeds. the user will be prompted to decide whether or not to open the file.AutomationSecurity = msoAutomationSecurityForceDisable Application. Syntax expression.AutomationSecurity = secAutomation End Sub . Setting ScreenUpdating to False does not affect alerts and will not affect security warnings. Visual Basic for Applications Sub Security() Dim secAutomation As MsoAutomationSecurity secAutomation = Application. Disables all macros in all files opened programmatically without showing any security alerts.AutomationSecurity expression A variable that represents an Application object.MsgBox "Automatic formatting for typing in hyperlinks is not enabled. and after opening the selected document.FileDialog(msoFileDialogOpen). msoAutomationSecurityForceDisable. if the user sets DisplayAlerts equal to False and AutomationSecurity to msoAutomationSecurityByUI. The DisplayAlerts setting will not apply to security warnings.AutomationSecurity Application." End If End Sub Application.Show Application. sets the automation security back to its original setting. MsoAutomationSecurity can be one of these MsoAutomationSecurity constants. Example This example captures the current automation security setting.AutomationSecurity Property Returns or sets an MsoAutomationSecurity constant that represents the security mode Microsoft Excel uses when programmatically opening files. Also. then there will be security warnings while the macro is running. Therefore. If a file that contains Microsoft Excel 4. you should be careful to reset this property to msoAutomationSecurityLow after programmatically opening a file.0 macros is opened programmatically. while the user is on Medium security level. changes the setting to disable macros. this property should be set immediately before and after opening a file programmatically to avoid malicious subversion. displays the Open dialog box. This allows the macro to trap file open errors.

" End Sub   Application.AutoPercentEntry expression A variable that represents an Application object.AutoRecover expression A variable that represents an Application object. 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.AutoPercentEntry = False   Application.AutoRecover.Time & " minutes.Application.AutoRecover Property Returns an AutoRecover object. Read/write Boolean. Example In this example.Build Property Returns the Microsoft Excel build number.Build expression A variable that represents an Application object.AutoPercentEntry Property True if entries in cells formatted as percentages aren’t automatically multiplied by 100 as soon as they are entered. Syntax expression. Visual Basic for Applications Application. Visual Basic for Applications Sub UseAutoRecover() Application. . Example This example enables automatic multiplication by 100 for subsequent entries in cells formatted as percentages. Syntax expression.Time = 5 MsgBox "The time that will elapse between each automatic " & _ "save has been set to " & _ Application.AutoRecover. Syntax expression. which backs up all file formats on a timed interval. Read-only Long. Remarks Valid time intervals are whole numbers from 1 to 120.

CalculationInterruptKey Property Sets or returns an XlCalculationInterruptKey constant that specifies the key that can interrupt Microsoft Excel when performing calculations." Case xlEscKey MsgBox "The calcuation interrupt key is set to 'Escape'" Case xlNoKey . This property is preserved even if you change the Calculation property. Read/write.Remarks It’s usually safer to test the Version property. unless you’re sure you need to know the build number. Visual Basic for Applications Application. Example In this example. Read/write Boolean. Select Case Application. Visual Basic for Applications If Application. Example This example tests the Build property.CalculateBeforeSave Property True if workbooks are calculated before they're saved to disk (if the Calculation property is set to xlManual).CalculationInterruptKey Case xlAnyKey MsgBox "The calcuation interrupt key is set to any key.CalculateBeforeSave expression A variable that represents an Application object.CalculationInterruptKey expression A variable that represents an Application object. Microsoft Excel determines the setting for the calculation interrupt key and notifies the user.Build > 2500 Then ' build-dependent code here End If Application. Visual Basic for Applications Sub CheckInterruptKey() ' Determine the calculation interrupt key and notify the user.Calculation = xlManual Application. Example This example sets Microsoft Excel to calculate workbooks before they're saved to disk. Syntax expression. Syntax expression.CalculateBeforeSave = True Application.

MsgBox "The calcuation interrupt key is set to no key. Read-only Long. Visual Basic for Applications If Application. the example sets the blnFullCalc variable to True. If the two version numbers are different. Otherwise.CalculationVersion <> _ Workbooks(1)." End Select End Sub Application.CalculationState expression A variable that represents an Application object.CalculationState Property Returns an XlCalculationState constant that indicates the calculation state of the application. Syntax expression.CalculationVersion Then .CalculationVersion Property Returns a number whose rightmost four digits are the minor calculation engine version number. a message displays the calculation state as "Not Done". for any calculations that are being performed in Microsoft Excel.CalculationState = xlDone Then MsgBox "Done" Else MsgBox "Not Done" End If End Sub Application. a message displays the calculation state as "Done". Example In this example. then this property returns 0. Syntax expression. Remarks If the workbook was saved in an earlier version of Excel and if the workbook hasn't been fully recalculated.CalculationVersion expression A variable that represents an Application object. Read-only. Visual Basic for Applications Sub StillCalculating() If Application. Example This example compares the version of Microsoft Excel with the version of Excel that the workbook was last calculated in. and whose other digits (on the left) are the major version of Microsoft Excel. Microsoft Excel checks to see if any calculations are being performed. If no calculations are being performed.

as shown in the following table. see the Remarks section). Syntax expression. Caller A custom function entered in a single cell A custom function that is part of an array formula in a range of cells An Auto_Open. Visual Basic for Applications Select Case TypeName(Application. Index Remarks This property returns information about how Visual Basic was called.Caller(Index) expression A variable that represents an Application object. or Auto_Deactivate macro A macro set by either the OnDoubleClick or OnEntry property The Macro dialog box (Tools menu). see the Remarks section). Auto_Activate.Caller) Case "Range" v = Application.Caller. This argument is used only when the property returns an array (for more information. Parameters Name Required/Optional Optional Data Type Variant Description An index to the array.Address Case "String" v = Application.Caller Case "Error" v = "Error" Case Else v = "unknown" End Select MsgBox "caller = " & v . or any caller not described above Return value A Range object specifying that cell A Range object specifying that range of cells The name of the document as text The name of the chart object identifier or cell reference (if applicable) to which the macro applies The #REF! error value Example This example displays information about how Visual Basic was called.Caller Property Returns information about how Visual Basic was called (for more information.blnFullCalc = True Else blnFullCalc = False End If Application. Auto_Close.

Syntax expression.Text = "First Quarter Sales" End With This example hides Chart1.ClipboardFormats Property Returns the formats that are currently on the Clipboard. as an array of numeric values. Visual Basic for Applications Application. For more information. Read-only Variant. If this argument is omitted. "Chart3". Example This example sets the text for the title of Chart1. Chart3.CellDragAndDrop Property True if dragging and dropping cells is enabled. Read/write Boolean.ChartTitle. Visual Basic for Applications Charts(Array("Chart1".CellDragAndDrop = True Application.Charts Property Returns a Sheets collection that represents all the chart sheets in the active workbook.Visible = False Application. "Chart5")). Visual Basic for Applications With Charts("Chart1") . Example This example enables dragging and dropping cells.CellDragAndDrop expression A variable that represents an Application object.Application. To determine whether a particular format is on the Clipboard.ClipboardFormats(Index) expression A variable that represents an Application object. the property returns the entire array of formats that are currently on the Clipboard. see the Index . and Chart5.Charts expression A variable that represents an Application object.HasTitle = True . Parameters Name Required/Optional Optional Data Type Variant Description The array element to be returned. compare each element in the array with the appropriate constant listed in the Remarks section. Syntax expression. Syntax expression.

COMAddIns Property Returns the COMAddIns collection for Microsoft Excel. Syntax expression. 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 deletes all custom command bars that aren’t visible.ClipboardFormats For Each fmt In aFmts If fmt = xlClipboardFormatRTF Then MsgBox "Clipboard contains rich text" End If Next Application. using this property with a Workbook object returns Nothing. Visual Basic for Applications aFmts = Application.CommandBars Property Returns a CommandBars object that represents the Microsoft Excel command bars.COMAddIns MsgBox "Number of COM add-ins available:" & _ objAI.Remarks section. Syntax expression. You can create an RTF object by copying text from a Word document. When a workbook is embedded in another application and activated by the user by double-clicking the workbook. . There is no programmatic way to return the set of command bars attached to a workbook. this property returns the set of built-in and custom command bars available to the application.COMAddIns expression A variable that represents an Application object. Example This example displays the number of COM add-ins that are currently installed. which represents the currently installed COM add-ins. Remarks Used with the Application object. Example This example displays a message box if the Clipboard contains a rich-text format (RTF) object. At all other times.Count Application. Read-only. Visual Basic for Applications Set objAI = Application. Read-only. using this property with a Workbook object returns the set of Microsoft Excel command bars available within the other application.CommandBars expression An expression that returns a Application object.

CommandBars If Not bar.Visible Then bar.Value This example displays the name of each worksheet in the active workbook.Worksheets expression A variable that represents an Application object. returns a Sheets collection that represents all the worksheets in the active workbook.BuiltIn And Not bar.Add newSheet. Parameters Name Required/Optional Data Description . Visual Basic for Applications MsgBox Worksheets("Sheet1").Visual Basic for Applications For Each bar In Application.Delete Next Application. Read-only Sheets object. Example This example displays the value in cell A1 on Sheet1 in the active workbook.Name Next ws This example adds a new worksheet to the active workbook and then sets the name of the worksheet. For a Workbook object. Remarks Using this property without an object qualifier returns all the worksheets in the active workbook.Wait(Time) expression A variable that represents an Application object. Visual Basic for Applications For Each ws In Worksheets MsgBox ws. use the Excel4MacroSheets property or the Excel4IntlMacroSheets property to return those sheets. Syntax expression.Range("A1").Name = "current Budget" Application. Visual Basic for Applications Set newSheet = Worksheets. Syntax expression.Wait Method Pauses a running macro until a specified time.Worksheets Property For an Application object. Returns True if the specified time has arrived. returns a Sheets collection that represents all the worksheets in the specified workbook. This property doesn’t return macro sheets.

Use the MakeConnection method before testing the IsValid property. Example .) data sources. With a CalculatedMember object you can check the validity of a calculated field or item in a PivotTable using the IsValid property. Remarks Use the Add method or the Item property of the CalculatedMembers collection to return a CalculatedMember object. Note The IsValid property will return True if the PivotTable is not currently connected to the data source. Visual Basic for Applications If Application.Type Time Required Variant The time at which you want the macro to resume. 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. in Microsoft Excel date format. OLAP data is organized hierarchically and stored in cubes instead of tables.Wait "18:23:00" This example pauses a running macro for approximately 10 seconds. background processes such as printing and recalculation continue. newMinute. Visual Basic for Applications Application.Wait(Now + TimeValue("0:00:10")) Then MsgBox "Time expired" End If 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. Example This example pauses a running macro until 6:23 P. today.M. The following example notifies the user if the calculated member is valid or not. instead of processing transactions. Visual Basic for Applications newHour = Hour(Now()) newMinute = Minute(Now()) newSecond = Second(Now()) + 10 waitTime = TimeSerial(newHour. However. This example assumes a PivotTable exists on the active worksheet that contains either a valid or invalid calculated member. newSecond) Application.Wait waitTime This example displays a message indicating whether 10 seconds have passed.

" Else MsgBox "The calculated member is not valid. Use the CalculatedMembers property of the PivotTable object to return a CalculatedMembers collection.PivotCaches.IsConnected = False Then pvtCache.Visual Basic for Applications Sub CheckValidity() Dim pvtTable As PivotTable Dim pvtCache As PivotCache Set pvtTable = ActiveSheet. On Error GoTo Not_OLEDB ' Check connection setting and make connection if necessary." End If End Sub   CalculatedMembers Collection A collection of all the CalculatedMember objects on the specified PivotTable. If pvtTable.ActiveWorkbook.MakeConnection End If ' Check if calculated member is valid.Item(1) ' Handle run-time error if external source is not an OLEDB data source.Item(1). If pvtCache. Remarks Each CalculatedMember object represents a calculated member or calculated measure. assuming a PivotTable exists on the active worksheet. The following example adds a set to a PivotTable.CalculatedMembers.PivotTables(1) Set pvtCache = Application. Visual Basic for Applications Example Sub UseCalculatedMember() Dim pvtTable As PivotTable .IsValid = True Then MsgBox "The calculated member is valid.

see PlotArea Object.ChartArea. Example The following example turns off the border for the chart area in embedded chart 1 on the worksheet named "Sheet1. so filling the plot area does not fill the chart area.Set pvtTable = ActiveSheet. the plot area has its own fill.BackColor. Variant:=1 End With ChartGroup Object Represents one or more series plotted in a chart with the same format. Example The following example sets the foreground color. background color.Line. _ ChartArea. _ Type:=xlCalculatedSet End Sub ChartArea Object Represents the chart area of a chart.Visible = True . Remarks The chart area includes everything.CalculatedMembers.[All Products]. each chart group contains one or more Series objects. For information about formatting the plot area. and each series contains one or more Points objects.Chart. Represents fill formatting for chart elements.SchemeColor = 17 .Format. including the plot area. Remarks Use the Fill property to return a ChartFillFormat object. For example." Visual Basic for Applications Worksheets("Sheet1").PivotTables(1) pvtTable.ChartObjects(1). containing all the series plotted with the line chart format. Remarks A chart contains one or more chart groups. containing all the series plotted with the bar chart format.ForeColor.TwoColorGradient Style:=msoGradientHorizontal.SchemeColor = 15 . Use the ChartArea property to return the ChartArea object. a single chart might contain both a line chart group.Fill .Children}'". Visual Basic for Applications With Charts(1). . and a bar chart group. The ChartGroup object is a member of the ChartGroups collection.Add Name:="[Beef]". However. and gradient for the chart area fill on Chart 1.Visible = False ChartFillFormat Object Used only with charts. _ Formula:="'{[Product].

Because the index number for a particular chart group can change if the chart format used for that group is changed. The following example displays the number of chart groups on embedded chart 1 on worksheet 1.Use ChartGroups(index).ChartGroups(1).Chart. each chart group contains one or more series. Charts(1). where index is the chart-group index number. or without an index number to return a ChartGroups collection. where index is the chart-group index number. The PieGroups method returns the collection of pie chart groups in a chart. to return a single ChartGroup object. containing all the series plotted with the bar chart format.HasDropLines = True Because the index number for a particular chart group can change if the chart format used for that group is changed. Visual Basic for Applications Charts(1).Activate ActiveChart. The following example adds drop lines to chart group 1 on chart sheet 1. it may be easier to use one of the named chart group shortcut methods to return a particular chart group. containing all the series plotted with the line chart format. The PieGroups method returns the collection of pie chart groups in a chart. a single chart might contain both a line chart group.ChartGroups(1). For example. ChartObject Object Represents an embedded chart on a worksheet. and each series contains one or more points.ChartGroups(1).HasDropLines = True If the chart has been activated. Each of these methods can be used with an index number to return a single ChartGroup object. it may be easier to use one of the named chart group shortcut methods to return a particular chart group.HasDropLines = True If the chart has been activated. and so on. MsgBox Worksheets(1). Each of these methods can be used with an index number to return a single ChartGroup object.ChartObjects(1).Count Use ChartGroups(index). Use the ChartGroups method to return the ChartGroups collection. the LineGroups method returns the collection of line chart groups.HasDropLines = True ChartGroups Object Represents one or more series plotted in a chart with the same format. Example The following example adds drop lines to chart group 1 on chart sheet 1. Visual Basic for Applications Charts(1). or without an index number to return a ChartGroups collection.ChartGroups(1). to return a single ChartGroup object. the LineGroups method returns the collection of line chart groups. Remarks .Activate ActiveChart. and so on. A chart contains one or more chart groups.ChartGroups. you can use ActiveChart: Charts(1). you can use the ActiveChart property. and a bar chart group. Remarks A ChartGroups collection is a collection of all the ChartGroup objects in the specified chart.

Fill. Use ChartObjects(index). Visual Basic for Applications Charts. _ ChartArea.Chart." Visual Basic for Applications Worksheets("sheet1"). where index is the embedded chart index number or name." Visual Basic for Applications Example Worksheets("Sheet1").ChartObjects(1). Visual Basic for Applications Charts.ChartWizard source:=Worksheets("Sheet1").Format. The following example puts rounded corners on the embedded chart named "Chart 1" on the worksheet named "Sheet1. Title:="February Data" End With .RoundedCorners = True Charts Collection A collection of all the chart sheets in the specified or active workbook. Properties and methods for the ChartObject object control the appearance and size of the embedded chart on the worksheet. to return a single ChartObject object.ChartObjects("chart 1"). The following example prints all chart sheets in the active workbook.Range("A1:A20"). Remarks Each chart sheet is represented by a Chart object.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 ChartObjects collection contains all the embedded charts on a single sheet.Pattern = msoPatternLightDownwardDiagonal The embedded chart name is shown in the Name box when the embedded chart is selected. The ChartObject object is a member of the ChartObjects collection. The following example adds a new line chart based on data in cells A1:A20 on the worksheet named Sheet1. _ Gallery:=xlLine. The following example sets the pattern for the chart area in embedded Chart 1 on the worksheet named "Sheet1. Example Use the Charts property to return the Charts collection. see the Chart or ChartObject topics. Visual Basic for Applications With Charts. Use the Name property to set or return the name of the ChartObject object.The ChartObject object acts as a container for a Chart object. This does not include charts embedded on worksheets or dialog sheets. For information about embedded charts.PrintOut Use the Add method to create a new chart sheet and add it to the workbook.Add . The following example adds a new chart sheet to the active workbook and places the new chart sheet immediately after the worksheet named Sheet1.

ForeColor.SeriesCollection(1).Item(1).RGB = rgbRed The Sheets collection contains all the sheets in the workbook (both chart sheets and worksheets).HasTitle = True . Visual Basic for Applications ActiveWindow.SheetViews. the foreground or background color of an object with a gradient or patterned fill. ChartTitle Object Represents the chart title.Sheet ColorFormat Object Represents the color of a one-color object. The following example adds a title to embedded chart one on the worksheet named "Sheet1. to return a single sheet. Visual Basic for Applications Charts(1).ChartTitle. Remarks . Remarks Use the ChartTitle property to return the ChartTitle object.Format.Fill. to return a single Chart object.Chart . The following example changes the color of series 1 on chart sheet 1 to red. Example The following example returns a ChartView object. or the pointer color." Visual Basic for Applications Example With Worksheets("sheet1"). Use Sheets(index).Text = "February Sales" End With ChartView Object Represents a view of a chart.Item(1) The following example returns a Chart object. Version Information Remarks Version Added: Excel 2007 The ChartView object is one of the objects that can be returned by the SheetViews collection. where index is the chart-sheet index number or name. similar to the Sheets collection. Visual Basic for Applications ActiveWindow.ChartObjects(1).SheetViews. The ChartView object applies only to chart sheets.Use Charts(index). where index is the sheet name or number. The ChartTitle object doesn’t exist and cannot be used unless the HasTitle property for the chart is True.

The color for the minimum threshold is then assigned to red and the maximum threshold to blue. 170) .RGB = RGB(128. Color scales are visual guides that help you understand data distribution and variation.TwoColorGradient msoGradientHorizontal.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). type. You can create a color scale formatting rule by using either the Add or AddColorScale method of the FormatConditions collection.AddShape(msoShapeRectangle.BackColor. The ColorScaleCriteria object.Fill . which is a child of a Range collection. You can apply either a two-color or a three-color scale to a range of data. Use one of the properties listed in the following table to return a ColorFormat object. Version Information Remarks Version Added: Excel 2007 All conditional formatting objects are contained within a FormatConditions collection object. A three-color scale also has a midpoint threshold. Visual Basic for Applications Set myDocument = Worksheets(1) With myDocument. and color to the minimum and maximum thresholds of a range. 90. you assign the value. For a two-color scale conditional format. 1 End With ColorScale Object Represents a color scale conditional formatting rule.Shapes. or data in a PivotTable report. 170. The following example adds a rectangle to myDocument and then sets the foreground color. 0) . which is a child of the ColorScale object. _ 90. is a collection of all of the ColorScaleCriterion objects for the color scale. and gradient for the rectangle's fill. 90. data in a table. Visual Basic for Applications Sub CreateColorScaleCF() . Each of these thresholds is determined by setting the properties of the ColorScaleCriteria object. background color. 0.ForeColor. 50). Example The following code example creates a range of numbers and then applies a two-color scale conditional formatting rule to that range. Use this property BackColor ForeColor BackColor ForeColor ForeColor ExtrusionColor With this object FillFormat FillFormat LineFormat LineFormat ShadowFormat ThreeDFormat To return a ColorFormat object that represents this The background fill color (used in a shaded or patterned fill) The foreground fill color (or simply the fill color for a solid fill) The background line color (used in a patterned line) The foreground line color (or just the line color for a solid line) The shadow color 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.RGB = RGB(170.

Visual Basic for Applications Sub CreateColorScaleCF() Dim cfColorScale As ColorScale 'Fill cells with sample data from 1 to 10 With ActiveSheet . Version Information Remarks Version Added: Excel 2007 To return the ColorScaleCriteria collection. use the ColorScaleCriteria property of the ColorScale object. 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.FormatColor.Range("C2") = 2 .Select 'Create a two-color ColorScale object for the created sample data range Set cfColorScale = Selection. Each criterion specifies the minimum.AddColorScale(ColorScaleType:=2) 'Set the minimum threshold to red and maximum threshold to blue cfColorScale.ColorScaleCriteria(1). 0) cfColorScale.ColorScaleCriteria(2).FormatConditions.Range("C1:C2").Color = RGB(0.Dim cfColorScale As ColorScale 'Fill cells with sample data from 1 to 10 With ActiveSheet .AutoFill Destination:=Range("C1:C10") End With .Range("C2") = 2 . 255) End Sub ColorScaleCriteria Collection A collection of ColorScaleCriterion objects that represents all of the criteria for a color scale conditional format.FormatColor.AutoFill Destination:=Range("C1:C10") End With Range("C1:C10").Range("C1:C2").Range("C1") = 1 . midpoint. 0.Color = RGB(255. Example The following code example creates a range of numbers and then applies a two-color scale conditional formatting rule to that range. 0.Range("C1") = 1 . or maximum threshold for the color scale.

FormatConditions.ColorStops.Degree = 135 .TintAndShade = 0 End With .Select 'Create a two-color ColorScale object for the created sample data range Set cfColorScale = Selection.FormatColor.ThemeColor = xlThemeColorDark1 .AddColorScale(ColorScaleType:=2) 'Set the minimum threshold to red and maximum threshold to blue cfColorScale.Gradient.ThemeColor = xlThemeColorDark1 .Clear End With With Selection.ColorStops.Interior.ColorStops.Interior.ThemeColor = xlThemeColorAccent1 .ColorScaleCriteria(2).Add(1) .5) . 255) End Sub ColorStop Object Represents the color stop point for a gradient fill in an range or selection. Visual Basic for Applications Example With Selection.Gradient.FormatColor.Interior .Gradient. The following example shows how to apply properties to the ColorStop.ColorStops. ThemeColor.Add(0) .Pattern = xlPatternLinearGradient . TintAndShade.TintAndShade = 0 End With With Selection.Color = RGB(0.ColorScaleCriteria(1).TintAndShade = 0 End With With Selection.Gradient.Interior. Version Information Remarks Version Added: Excel 2007 The ColorStop collection allows you to set properties for the cell fill including Color.Gradient.Color = RGB(255.Add(0.Range("C1:C10"). 0. 0) cfColorScale. 0.

You will notice that because there is an extremely low and high value in the range. The following example hides comment two on worksheet one. where index is the comment number. to return a single comment from the Comments collection. the middle values have data bars that are of similiar length. Example Use the Comments property to return the Comments collection. Visual Basic for Applications Set cmt = Worksheets(1).Range("e5").Comments For Each c In cmt c. Visual Basic for Applications With Worksheets(1).Visible = False ConditionValue Object Represents how the shortest bar or longest bar is evaluated for a data bar conditional formatting rule.Text "reviewed on " & Date End With Use Comments(index). Version Information Remarks Version Added: Excel 2007 The ConditionValue object is returned using either the MaxPoint or MinPoint property of the Databar object. The following example hides all the comments on worksheet one. Example The following example creates a range of data and then applies a data bar to the range. the sample code uses the ConditionValue object to change how the thresholds are evaluated to percentiles. Remarks Each comment is represented by a Comment object.AddComment .Visible = False . 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. Visual Basic for Applications . Visual Basic for Applications Worksheets(1).Comments(2). To disambiguate the middle values. The following example adds a comment to cell E5 on worksheet one.Comments Object A collection of cell comments.Visible = False Next Use the AddComment method to add a comment to a range.

Sub CreateDataBarCF()

Dim cfDataBar As Databar

'Create a range of data with a couple of extreme values With ActiveSheet .Range("D1") = 1 .Range("D2") = 45 .Range("D3") = 50 .Range("D2:D3").AutoFill Destination:=Range("D2:D8") .Range("D9") = 500 End With

Range("D1:D9").Select

'Create a data bar with default behavior Set cfDataBar = Selection.FormatConditions.AddDatabar MsgBox "Because of the extreme values, middle data bars are very similar"

'The MinPoint and MaxPoint properties return a ConditionValue object 'which you can use to change threshold parameters cfDataBar.MinPoint.Modify newtype:=xlConditionValuePercentile, _ newvalue:=5 cfDataBar.MaxPoint.Modify newtype:=xlConditionValuePercentile, _ newvalue:=75

End Sub Connections Object
A collection of Connection objects for the specified workbook.

Version Information Example

Version Added: Excel 2007

The following example shows how to add a connection to a workbook from an existing file.
Visual Basic for Applications

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.
Shape type AutoShapes, WordArt, pictures, and OLE objects Freeforms Connection site numbering scheme The connection sites are numbered starting at the top and proceeding counterclockwise. 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.
Visual Basic for Applications

Set mainshape = ActiveWindow.Selection.ShapeRange(1) With mainshape bx = .Left + .Width + 50 by = .Top + .Height + 50 End With With ActiveSheet For j = 1 To mainshape.ConnectionSiteCount With .Shapes.AddConnector(msoConnectorStraight, _ bx, by, bx + 50, by + 50) .ConnectorFormat.EndConnect mainshape, j .ConnectorFormat.Type = msoConnectorElbow .Line.ForeColor.RGB = RGB(255, 0, 0) l = .Left t = .Top End With With .Shapes.AddTextbox(msoTextOrientationHorizontal, _ l, t, 36, 14) .Fill.Visible = False .Line.Visible = False .TextFrame.Characters.Text = j End With Next j

End With
The following example adds two rectangles to myDocument and connects them with a curved connector.
Visual Basic for Applications

Set myDocument = Worksheets(1) Set s = myDocument.Shapes Set firstRect = s.AddShape(msoShapeRectangle, 100, 50, 200, 100) Set secondRect = s.AddShape(msoShapeRectangle, 300, 300, 200, 100) Setc c = s.AddConnector(msoConnectorCurve, 0, 0, 0, 0) With c.ConnectorFormat .BeginConnect ConnectedShape:=firstRect, ConnectionSite:=1 .EndConnect ConnectedShape:=secondRect, ConnectionSite:=1 c.RerouteConnections End With 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 Remarks

Version Added: Excel 2007

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.
Visual Basic for Applications

Sub CreateDataBarCF()

Dim cfDataBar As Databar

'Create a range of data with a couple of extreme values With ActiveSheet .Range("D1") = 1 .Range("D2") = 45 .Range("D3") = 50 .Range("D2:D3").AutoFill Destination:=Range("D2:D8")

MinPoint. Once an Error object is returned. to display a message stating the situation.Range("D9") = 500 End With Range("D1:D9").Formula = "=A2+A3" Application. Remarks Use the Item property of the Errors object to return an Error object. where index identifies the error type.Select 'Create a data bar with default behavior Set cfDataBar = Selection. _ newvalue:=75 End Sub Error Object Represents a spreadsheet error for a range..FormatConditions. Visual Basic for Applications Sub CheckEmptyCells() Dim rngFormula As Range Set rngFormula = Application.Modify newtype:=xlConditionValuePercentile.AddDatabar MsgBox "Because of the extreme values. middle data bars are very similar" 'The MinPoint and MaxPoint properties return a ConditionValue object 'which you can use to change threshold parameters cfDataBar.ErrorCheckingOptions. _ newvalue:=5 cfDataBar.Modify newtype:=xlConditionValuePercentile.Range("A1") ' Place a formula referencing empty cells. in conjunction with the Errors property to check whether a particular error checking option is enabled.EmptyCellReferences = True ' Perform check to see if EmptyCellReferences check is on. . Example The following example creates a formula in cell A1 referencing empty cells. Note Be careful not to confuse the Error object with error handling features of Visual Basic. Range("A1").MaxPoint. you can use the Value property. and then it uses Item(index).

Follow Next . Visual Basic for Applications For Each h in Worksheets(1)." Else MsgBox "The empty cell references error checking feature is not on. If the OddAndEvenPagesHeaderFooter property is True. Use the OddAndEvenPagesHeaderFooter property with the PageSetup object to specify different odd and even page headers and footers. you can return an odd header or footer by using wdHeaderFooterPrimary. Visual Basic for Applications With ActiveWorksheet. and you can return an even header or footer by using wdHeaderFooterEvenPages.PageNumbers.Hyperlinks If Instr(h. The following example adds page numbers to the primary footer in the first section of the active workbook.Footers(wdHeaderFooterPrimary).Add End With Hyperlinks Object Represents the collection of hyperlinks for a worksheet or range.Name. Use the DifferentFirstPageHeaderFooter property with the PageSetup object to specify a different first page. The following example checks the hyperlinks on worksheet one for a link that contains the word Microsoft. Note You cannot add HeaderFooter objects to the HeadersFooters collection.If rngFormula. The HeadersFooters collection includes all headers and footers in the specified workbook section. Example Use the Add method with the PageNumbers object to add a page number to a header or footer. "Microsoft") <> 0 Then h." End If End Sub HeaderFooter Object Represents a single header or footer. Example Use the Hyperlinks property to return the Hyperlinks collection. Version Information Remarks Version Added: Excel 2007 You can also return a single HeaderFooter object by using the HeaderFooter property with a Selection object.Item(xlEmptyCellReferences).Sections(1) . Remarks Each hyperlink is represented by a Hyperlink object.Errors.Value = True Then MsgBox "The empty cell references error checking feature is enabled. The HeaderFooter object is a member of the HeadersFooters collection.

InputMessage = "Enter an integer from five to ten" .Use the Add method to create a hyperlink and add it to the Hyperlinks collection.Add .Hyperlinks. _ Minimum:="5".Validation _ .Range("E5"). _ AlertStyle:=xlValidAlertInformation. Visual Basic for Applications With Worksheets(1) . Visual Basic for Applications With Range("e5"). Maximum:="10" .ErrorTitle = "Integers" .InputTitle = "Integers" .ErrorMessage = "You must enter a number from five to ten" End With   . Visual Basic for Applications Range("e5").Add Type:=xlValidateWholeNumber. Example Use the Validation property to return the Validation object.microsoft. "=$A$1:$A$10" Use the Add method to add data validation to a range and create a new Validation object. "http://example.Modify xlValidateList. xlValidAlertStop. The following example adds data validation to cell E5. The following example changes the data validation for cell E5.com" End With Validation Object Represents data validation for a worksheet range.Validation . The following example creates a new hyperlink for cell E5.

Sign up to vote on this title
UsefulNot useful