Programming Microsoft Excel
Programming Microsoft Excel
Programming
Microsoft Excel
Objectives
Explore the top-level objects in the Excel object model.
Show how to work with data in cells on a worksheet.
Explain how to save form data to a worksheet.
Create a chart from VBA code.
Figure 1 shows a simplified version of the Microsoft Excel object model. For
the complete object model, see Online Help or go to the Microsoft web site, at
http://www.microsoft.com/OfficeDev/Articles/OMG/default.htm.
TIP: If you want to explore Microsoft Excels objects, properties, and methods,
head to the Object Browser, and press F1 for context-sensitive Help.
When youre programming in Microsoft Excel, you dont always need to refer
to the Application object explicitly. If youre using a property or method that
appears under the Globals class in the Object Browser, then you dont need to
specify the Application object. However, if youre using a property or method
that appears only under the Application class, and not also in the Globals class,
then you do need to explicitly refer to the Application object.
For example, you dont need to use the Application object when you refer to a
member of the Workbooks collection, because the Workbooks property is
global. This code makes a workbook the active workbook in Microsoft Excel:
Workbooks(1).Activate
However, you do need to use it when you call a method of the Application
object. The GetOpenFileName method of the Application object shows the
File Open dialog box, and returns a string containing the name of the file
chosen by the user:
strFileName = Application.GetOpenFilename(conFilter)
ActiveWorkbook.Save
The ActiveWorkbook property is convenient, but be careful when you use it. If
more than one workbook is open, the active workbook may not be the one your
code is expecting! Use the Activate method to make an open workbook the
active workbook.
You can open a workbook using the Open method of the Workbooks
collection, and assign it to an object variable:
You can create a new workbook with the Add method, and save it with the
SaveAs method:
With ActiveWorkbook
Debug.Print .Name
Debug.Print .Path
Debug.Print .FullName
End With
Use the Worksheets property with an index value or the worksheets name.
Debug.Print ActiveWorkbook.Worksheets(1).Name
ActiveWorkbook.ActiveSheet.Copy
The Worksheet object is used most often when referring to another object. So
lets move on to the objects that appear beneath it in the object model.
Referring to a Range
In order to refer to a range, you need to specify either a name or an address for
the range. The following are just a few of the ways to refer to a range.
Debug.Print Worksheets(1).Range("A1").Value
Worksheets(1).Range("A1:B5").Font.Bold = True
To refer to a named range, you can just use the name of the range:
Debug.Print _
Worksheets(1).Range("ProductName").Rows.Count
TIP: To create a named range in Microsoft Excel, select the cells you want to
include in the range, then type a name for the range into the Name Box in the
upper left-hand corner of Microsoft Excel. You can also create a named range
programmatically, by using the Add method of the Names collection.
To use the CurrentRegion property, activate a cell within the data region by
using the Activate method on the range that represents that cell.
Sub DataRegion()
Dim rng As Range
For example, suppose you want to get the value of the first cell in the
ProductName range. Rather than figuring out the address for that cell, you can
use the Cells property as follows:
The Cells property takes as arguments the row and column youre interested in
within the range. In other words, Cells(1, 1) returns the cell in the upper
leftmost corner of the range. Cells(2, 1) returns the cell in the first
column and second row of the range, and so on. The Cells property evaluates
rows and columns relative to the range, so it doesnt matter where the range is
on the worksheet Cells(1, 1) always returns the first cell.
To try this example, view the Schedule worksheet in vba.xls. Select a group of
two or more cells, then click the AutoFill Weekdays toolbar button as shown
in Figure 2.
Figure 2. Clicking the toolbar button fills the selected cells with a repeating series
of weekdays.
Sub FillWeekdays()
Dim rng As Range
Dim rngStart As Range
Exit_FillWeekdays:
Exit Sub
End Sub
The first thing this procedure does is to use the Selection property to return a
range representing the users selection. It then counts the number of cells in the
range to make sure the user has selected more than one cell. If not, then the
procedure exits.
Assuming the user has selected at least two cells, the procedure then checks to
see how many columns the user has selected. If its more than one, then it
redefines the range to include only the first column.
Next, the procedure returns a range, rngStart, that represents the first cell in
the selection, and gives that cell the seed value of Monday. Finally, it calls
the AutoFill method on rngStart, specifying the cells to be filled as the
selection range, and that they are to be filled with weekdays.
First, take a look at frmSaveData. Run the form, enter some data into the text
See frmSaveData boxes, and click OK. The data is saved to the first row in the Microsoft Excel
worksheet beneath the column headings (see Figure 3). The next set of data
entered is saved to the next row of the worksheet, and so on.
The Click event procedure for the OK button contains the code that inserts the
new data into the worksheet:
Whats this code doing? First, it uses the CurrentRegion property to return a
range containing all of the contiguous data around the active cell. The range
returned by the CurrentRegion property is bounded by at least one empty row
and one empty column. By adding 1 to the number of rows in the current
region, you can be sure youre working with an empty row. You can use the
resulting row number as an argument to the Cells property.
Next, the procedure assigns the value of the Value property for each text box
on the form to the Value property for a cell in the active worksheet. Finally, it
clears the data from the form and sets the focus to the first text box, so the user
can enter another record.
These two objects hold different places in the object model. The Chart object
is a member of the workbooks Charts collection, and the ChartObject object is
a member of a worksheets ChartObjects collection (see Figure 4).
Figure 4. Charts and ChartObjects occupy different positions in the object model.
The primary differences between the Chart and ChartObject are that Microsoft
Excel provides properties for the ChartObjects frame within the worksheet.
For this chapter, well just focus on Chart objects.
create charts. This method emulates the behavior of the Microsoft Excel
ChartWizard, which comes up when you choose the Insert|Chart menu item.
There are quite a few arguments, but dont be daunted. All of the arguments
are optional, so lets take a look at a few of the important ones:
Creating a Chart
See CreateChart in Now lets try creating a chart using the ChartWizard method. Open the
basBuildChart basBuildChart module in vba.xls and run the CreateChart procedure to practice
this exercise.
The chart were creating plots sales data from the Sales worksheet. To make it
easy to identify, weve created a named range called TotalSales that
encompasses all the data on the worksheet. The procedure will use this range
as the source for the chart. The following table shows the data in the range, as
it appears in Microsoft Excel:
Employee TotalSales
Heres the CreateChart procedure. It adds a new chart to the Charts collection,
then uses the ChartWizard method to provide all the data needed to create the
chart we want. Finally, it adds some additional formatting to the chart.
Sub CreateChart()
Dim wbk As Workbook
Dim wks As Worksheet
Dim cht As Chart
Dim rng As Range
Dim intCount As Integer
We end up with a chart that looks like the one shown in Figure 5:
Summary
Some of the key objects in the Microsoft Excel object model are:
Application, Workbook, Worksheet, Range, and Chart.
The Range object is the object you use to work with sets of cells. You
can refer to ranges using an address such as A1:B5, or by using a name
if youve created a named range.
The Cells property of the Range object enables you to set or retrieve a
value from a cell.
If you want to use a form for data entry, you can save form data to a
worksheet.
The Chart object represents a chart, and is a member of the Charts
collection of the Workbook object.
You can generate a chart from VBA by using the ChartWizard
method.