42
The Recorded Macro
The recorded macro should look like the following:
Sheets(“Sales”).Select
ActiveSheet.Shapes.AddChart.Select
ActiveChart.SetSourceData Source:=Range(“Sales!$A$3:$D$7”), PlotBy:= _
xlColumns
ActiveChart.ChartType = xlColumnClustered
Charts.Add
ActiveChart.ChartArea.Select
ActiveChart.PlotBy = xlRows
ActiveChart.ApplyLayout (1)
ActiveChart.ChartTitle.Select
ActiveChart.ChartTitle.Text = “Mangoes”
ActiveChart.ChartArea.Select
Although you inserted a new chart sheet, the recorded macro uses the AddChart method of the Shapes
object to create an embedded chart in the Sales worksheet. (Note that the recorder prefers to refer to a
ChartObjectas a Shapeobject, which is an alternative pointed out at the beginning of this chapter.) It
uses the SetSourceData method to define the ranges plotted by the active chart and sets the chart’s
ChartTypeproperty.
The macro then uses the Addmethod of the Charts collection to create a new chart sheet. At this point,
the embedded chart is used to create the new chart sheet. The PlotByproperty changes the orientation
of the chart, and the ApplyLayoutmethod applies the selected format so that a title appears. The Text
property of the ChartTitle object is assigned the string “Mangoes”. Finally, the macro records that you
selected the chart area.
Adding a Chart Sheet Using VBA Code
The recorded code is a bit odd. There is no need to create an embedded chart. You can simply add a
chart sheet and set its properties directly. You can also create an object variable, so that you have a sim-
ple and efficient way of referring to the chart in subsequent code. Rather than limit yourself to the preset
layouts, you can select the chart features you want, such as a title. There is no need to plot by columns
and then plot by rows. The following code incorporates these changes:
Sub AddChartSheet()
Dim cht As Chart
‘Create new chart sheet
Set cht = Charts.Add
With cht
‘Specify source data and orientation
.SetSourceData Source:=Sheets(“Sales”).Range(“A3:D7”), _
PlotBy:=xlRows
.ChartType = xlColumnClustered
‘Add a title and assign it a value
184
Chapter 8: Charts