30.04.2017 Views

4523756273

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

224<br />

Part III: Programming Concepts<br />

When you click an embedded chart, Excel actually selects an object inside the<br />

ChartObject object. You can select the ChartObject itself by pressing Ctrl<br />

while clicking the embedded chart.<br />

Modifying the chart type<br />

Here’s a confusing statement for you: A ChartObject object acts as a container<br />

for a Chart object. Read that a few times, and it might actually make<br />

sense.<br />

To modify a chart with VBA, you don’t have to activate the chart. Rather, the<br />

Chart method can return the chart contained in the ChartObject. Are you thoroughly<br />

confused yet? The following two procedures have the same effect —<br />

they change the chart named Chart 1 to an area chart. The first procedure<br />

activates the chart first and then works with the active chart. The second<br />

procedure doesn’t activate the chart. Rather it uses the Chart property to<br />

return the Chart object contained in the ChartObject object.<br />

Sub ModifyChart1()<br />

ActiveSheet.ChartObjects(“Chart 1”).Activate<br />

ActiveChart.Type = xlArea<br />

End Sub<br />

Sub ModifyChart2()<br />

ActiveSheet.ChartObjects(“Chart 1”) _<br />

.Chart.Type = xlArea<br />

End Sub<br />

Looping through the<br />

ChartObjects collection<br />

This example changes the chart type of every embedded chart on the active<br />

sheet. The procedure uses a For-Next loop to cycle through each object in<br />

the ChartObjects collection, access the Chart object in each, and change its<br />

Type property.<br />

Sub ChartType()<br />

Dim cht As ChartObject<br />

For Each cht In ActiveSheet.ChartObjects<br />

cht.Chart.Type = xlArea<br />

Next cht<br />

End Sub

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!