Microsoft Office Tutorials and References
In Depth Information
Determining the Context for a Macro
The ModifyChart1 procedure uses the Deselect method to “deactivate” a chart.
This action is similar to pressing Esc when an embedded chart is activated. One key
difference, however, is that the previously selected worksheet cell or range is not
Determining the Context
for a Macro
In many cases, your macros may require that a specific type of object be selected.
For example, a macro may be written such that it requires that a chart be active or
that a range is selected. The examples in this section demonstrate how to write code
to ensure that the macro is running in the proper context.
Ensuring that a chart is selected
The simple macro that follows adds a title to the active chart (the title consists of
the contents of cell A1). If a chart is not active when this macro is executed, you’ll
see the rather cryptic error message shown in Figure 16-1.
Sub AddTitle()
With ActiveChart
.HasTitle = True
.ChartTitle.Text = Range(“A1”)
End With
End Sub
Figure 16-1: This error message appears
if a chart is not active.
To prevent this error (and make the macro a bit more user friendly), add a few
lines of code that check for the existence of an active chart. If there is no active
chart, the user gets a message to that effect and the procedure ends. The AddTitle
macro follows, showing the modification that checks for an active chart.
Search JabSto ::

Custom Search