Tải bản đầy đủ - 0trang
Table 18-2. Members That Return Objects
Let us discuss some of the members in Table 18-1.
This method activates the worksheet, as in:
This property is True if the AutoFilter drop-down arrows are currently displayed on the
worksheet. (Also see the FilterMode property, discussed later in this section). Note that
we can set this property to False to remove the arrows, but we cannot set it to True. To
display the AutoFilter arrows, we use the AutoFilter method, which is discussed in
This method calculates all cells in the worksheet. (Note that the method applies to
workbooks and specific ranges as well.) The syntax is simply:
This property returns the code name for the worksheet (it also applies to workbook and
chart objects). The code name can be used in place of any expression that returns the
worksheet. The code name can also be set in the Properties window. It is referred to as
(name) to distinguish it from the Name property.
To illustrate, suppose that we have a worksheet whose code name is SheetCodeName and
whose name is SheetName. Then the following are equivalent:
Note that when we first create a worksheet, the name and code name are the same. The
two names can then be changed independently. However, the code name can be changed
only at design time; it cannot be changed with code at run time.
The Copy method has multiple syntaxes. To copy a worksheet, we use the syntax:
where the optional Before parameter is the sheet before which the copied sheet will be
placed and the After parameter is the sheet after which the copied sheet will be placed.
(Only one of Before or After is allowed at one time.)
Note that if neither Before nor After is specified, Excel will copy the worksheet to a
To illustrate, the following code copies the active worksheet and places the copy at the
end of the list of current worksheets:
This method simply deletes the worksheet. The syntax is:
EnableCalculation property (R/W Boolean)
When this property is True, Excel automatically recalculates the worksheet when
necessary. Otherwise, the user must request a recalculation. Note that when this property
is first set to True, Excel will do a recalculation.
The Evaluate method converts an Excel name to an object or a value. We discussed the
details of this method in Chapter 16.
FilterMode property (Read-Only Boolean)
This property is True if the worksheet is in filter mode. Thus, for instance, if the
AutoFilter arrows are displayed but no filtering has taken place, then AutoFilterMode is
True whereas FilterMode is False. Once filtering is actually performed, then
FilterMode is True. Put another way, the FilterMode property indicates whether there are
hidden rows due to filtering.
The Move method moves the worksheet to another location in the workbook. The syntax
where the parameters have the same meaning as in the Copy method, discussed earlier in
Name property (R/W String)
This property returns or sets the name of the worksheet, as a string.
This property returns the Names collection representing all the worksheet-specific names.
For more on Name objects, see Chapter 16.
This method pastes the contents of the Clipboard onto the worksheet, using a specified
format. The most commonly used syntax is simply:
where Format specifies the format of the data to paste, as a string. For instance, the
following code pastes data in Word document format (assuming that it exists on the
ActiveSheet.PasteSpecial "Microsoft Word Document"
To learn the syntax of other Format strings, you can copy the desired object and then
check Excel's Paste Special dialog box.
Note that we must select the destination range before using the PasteSpecial method.
The PrintOut method prints a worksheet. (The method also applies to Workbook and
Range objects.) The syntax is:
WorksheetObject.PrintOut(From, To, Copies, _
Preview, ActivePrinter, PrintToFile, Collate)
Note that all of the parameters to this method are optional.
The From parameter specifies the page number of the first page to print, and the To
parameter specifies the last page to print. If omitted, the entire object (range, worksheet,
etc.) is printed.
The Copies parameter specifies the number of copies to print. The default is 1.
Set Preview to True to invoke print preview rather than printing immediately. The
default is False.
ActivePrinter sets the name of the active printer.
Setting PrintToFile to True causes Excel to print to a file. Excel will prompt the user
for the name of the output file. (Unfortunately, there is no way to specify the name of the
output file in code.)
The Collate parameter should be set to True to collate multiple multipage copies.
This method invokes Excel's print preview feature for the worksheet. Its syntax is:
This method protects a worksheet from modification. Its syntax is:
WorksheetObject.Protect(Password, DrawingObjects, _
Contents, Scenarios, UserInterfaceOnly)
(Note that the syntax varies from the same method of the Workbook object.)
The optional Password parameter is a string that specifies a case-sensitive password for
The optional DrawingObjects parameter should be set to True to protect shapes. The
default value is False.
The optional Contents parameter should be set to True, the default, to protect the cells
in the worksheet.
The optional Scenarios parameter should be set to True, the default, to protect
The Protect method allows independent protection of cells from changes by the user and
by code. In particular, if UserInterfaceOnly is set to True, then the user cannot
make changes to the worksheet, but changes can be made through code. On the other
hand, if UserInterfaceOnly is False (the default), then neither the user nor the
programmer can alter the worksheet. Note that it is not the macros themselves that are
protected, as the help documentation seems to indicate. Rather, the worksheet is protected
from the effect of the macros.
Note also that if the UserInterfaceOnly argument is set to True when protecting a
worksheet and then the workbook is saved, the entire worksheet (not just the interface)
will be protected when the workbook is reopened. To unprotect the worksheet but
reenable user interface protection, we must reapply the Protect method with
UserInterfaceOnly set to True.
ProtectionMode property (Read-Only)
This property is True if user-interface-only protection is turned on (via the Protect
method). Its default value is False.
This method saves changes to the worksheet in a different file. Its syntax is:
WorksheetObject.SaveAs(Filename, FileFormat, Password, _
WriteResPassword, ReadOnlyRecommended, CreateBackup, _
AddToMru, TextCodePage, TextVisualLayout)
The Filename parameter specifies the filename to use for the newly saved disk file. If a
path is not included, Excel will use the current folder.
The FileFormat parameter specifies the file format to use when saving the file. Its
value is one of the XlFileFormat constants described in our discussion of the
FileFormat property in Chapter 17.
The Password parameter specifies the password to use when saving the file and can be
set to any case-sensitive string of up to 15 characters.
The WriteResPassword parameter is a string that specifies the write-reservation
password for this file. If a file is saved with a write-reservation password and this
password is not supplied when the file is next opened, the file will be opened as read-only.
We can set the ReadOnlyRecommended parameter to True to display a message when
the file is opened, recommending that the file be opened as read-only.
Set the CreateBackup parameter to True to create a backup file.
Set the AddToMru parameter to True to add the workbook to the list of recently used
files. The default value is False.
The remaining parameters are not used in the U.S. English version of Excel.
This property returns or sets the range where scrolling and cell selection is allowed. The
value should be an A1-style range reference. For instance, the code:
ActiveSheet.ScrollArea = "A1:B200"
allows cell selection and scrolling only within the range A1:B200. To remove any
restrictions on cell selection and scrolling, set this property to an empty string, as in:
ActiveSheet.ScrollArea = ""
Note that setting the scroll area has nothing to do with freezing panes.
This method selects the worksheet. This is not the same as making it active through the
Activate method. In fact, several sheets can be selected at one time (to delete them, for
instance). The syntax is:
where Replace is set to True to replace the current selection with the specified
worksheet, rather than including the worksheet in the current selection.
This method sets the background graphic for a worksheet (or chart). The syntax is:
where FileName is the name of the graphic file to use for the background.
This method displays the data form associated with the worksheet. Note that for the
ShowDataForm method to work without generating an error, Excel must be able to
determine that the current selection is part of a list. For information on the use of data
forms, see the Excel 8 help topic "Guidelines for creating a list on a worksheet" or the
Excel 9 help topic "About data forms."
The syntax of this method is simply:
Note that the procedure in which the ShowDataForm method is called will pause while
the data form is displayed. When the data form is closed, the procedure will resume at the
line following the call to ShowDataForm. (In other words, the data form is modal.)
Figure 18-2 illustrates the data form for a worksheet.
Figure 18-2. A data form
This method removes protection from a worksheet. It has no effect if the worksheet is not
protected. The syntax is:
where Password is the password used to protect the worksheet (if any). If we omit this
argument for a sheet that is password-protected, Excel will prompt the user for the
This ostensibly very useful property returns a Range object that represents the smallest
rectangular region that encompasses any currently used cells.
Unfortunately, the UsedRange property has had a rather rocky history in past versions of
Excel, and my experience is that the problems have not been completely resolved in Excel
97. (Unfortunately, I know of no single test to check the reliability of this property, and I
have not yet used Excel 9 long enough to make a definitive statement about this version.)
Thus, I strongly suggest that you use this method with caution, for it sometimes seems to
include cells that once had contents but have since been completely cleared.
At the end of Chapter 19, we will give an example function that can be used to compute
the correct used range.
This property returns True if the worksheet is visible and False otherwise. However, in
addition to setting this property to True or False, we can also set this property to
xlVeryHidden, in which case the only way to make the worksheet visible is by setting
this property to True in code. Hence, the user cannot make the worksheet visible.
18.2 Children of the Worksheet Object
Let us discuss a few of the children of the Worksheet object. Others will be discussed in later
The Comments property returns the Comments collection, which consists of all Comment
objects (comments) in the worksheet. We will discuss the Comment object in Chapter 19.
The Names collection
We discussed the Names collection and Name objects in Chapter 16, and so we refer the
reader to that earlier discussion.
The Outline object
To illustrate Excel outlining using code, consider the worksheet shown in Figure 18-3.
Our goal is to produce the outline in Figure 18-4.
Figure 18-3. Illustrating Excel outlines
Figure 18-4. The end result
The first step in obtaining the outline in Figure 18-4 is to set the properties of the Outline
object for this worksheet. The Outline property of the Worksheet object returns an
Outline object, so we begin with:
.SummaryRow = xlBelow
.AutomaticStyles = False
Setting the SummaryRow property to xlBelow tells Excel that our summary rows (the
subtotal and total rows) lie below the detailed data. Thus, Excel will place the
expansion/contraction buttons (the small buttons displaying minus signs in Figure 18-4) at
the appropriate rows.
Setting AutomaticStyles to False prevents Excel from tampering with our formatting.
Otherwise, Excel would remove the boldfacing on the summary rows.
As you can see in Figure 18-4, we want to make the following groupings:
For this, we use the Group method of the Range object. In particular, the following code
accomplishes the desired grouping, resulting in Figure 18-4:
Note that the SummaryColumn property of the Outline object governs the location of the
expansion/contraction buttons when columns grouped.
To expand or collapse levels, the user can click the small numbered buttons at the top of
the leftmost column in Figure 18-4. Clicking on button number X results in all levels
above X being completely expanded and all levels below and including X being
completely contracted. Thus, all rows at level X and above are made visible, but no levels
below X are visible.
The same thing can be accomplished using the ShowLevels method of the Outline object,
whose syntax is:
For instance, the code:
is equivalent to clicking on the button labeled 2 and has the effect of showing all levels
above and including level 2, as pictured in Figure 18-5.
Figure 18-5. Outline collapsed to level 2
The PageSetup object
The PageSetup object represents the page formatting (such as margins and paper size) of
an Excel worksheet. Each of the page-formatting options is set by setting a corresponding
property of the PageSetup object.
The PageSetup property of the Worksheet object returns the worksheet's PageSetup object.
The properties and methods of the PageSetup object are shown in Table 18-3. (All of the
items in Table 18-3 are properties except the PrintQuality method.) Most of the members
in Table 18-3 are self-explanatory (and hold no real surprises), so we will not discuss
Table 18-3. Members of the PageSetup Object
To illustrate, the following code sets some of the properties of the active worksheet:
.LeftMargin = Application.InchesToPoints(1)
.RightMargin = Application.InchesToPoints(1)
.PrintTitleRows = "A1"
.PaperSize = xlPaperLetter
Note the use of the InchesToPoints function, which is required if we want to express
units in inches, since most of the formatting properties require measurement in points.
Referring to Figure 18-6, the PrintTitleRows property will cause the word Report, which
lies in cell A1, to appear on each page of the printout.
Figure 18-6. A worksheet and the PrintTitleRows property
18.3 Protection in Excel XP
Excel XP introduces some additional protection features, beginning with the Protection object,
which we discuss next.
18.3.1 The Protection Object
When you protect a worksheet, Excel permits you to specify that certain operations are still
permitted on unlocked cells. At the user level, this is done through the Protection dialog box. At
the programming level, it is done through the properties of the Protection object. Most of these
properties (listed below) are self-explanatory. Note that all of these properties except
AllowEditRanges are Boolean.