18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

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

VBA Examples 44<br />

If Book.Name ThisWorkbook.Name Then<br />

Book.Close savechanges:=True<br />

End If<br />

Next Book<br />

ThisWorkbook.Close savechanges:=True<br />

End Sub<br />

The procedure uses an If statement within the For-Next loop to determine whether the workbook is the<br />

workbook that contains the code. This is necessary because closing the workbook that contains the procedure<br />

would end the code, and subsequent workbooks would not be affected.<br />

Working with Charts<br />

Manipulating charts with VBA can be confusing, mainly because of the large number of objects involved. To<br />

get a feel for working with charts, turn on the macro recorder, create a chart, and perform some routine<br />

chart editing. You may be surprised by the amount of code that’s generated.<br />

When you understand how objects function within in a chart, however, you can create some useful macros.<br />

This section presents a few macros that deal with charts. When you write macros that manipulate charts,<br />

you need to understand some terminology. An embedded chart on a worksheet is a ChartObject object,<br />

and the ChartObject contains the actual Chart object. A chart on a chart sheet, on the other hand, does<br />

not have a ChartObject container.<br />

It’s often useful to create an object reference to a chart (see “Simplifying object references,” later in this<br />

chapter). For example, the following statement creates an object variable (MyChart) for the embedded<br />

chart named Chart 1 on the active sheet.<br />

Dim MyChart As Chart<br />

Set MyChart = ActiveSheet.ChartObjects(“Chart 1”)<br />

The following sections contain examples of macros that work with charts.<br />

ON the CD-ROM<br />

These macros are available on the companion CD-ROM. The file is named chart macros.xlsm.<br />

Modifying the chart type<br />

The following example changes the chart type of every embedded chart on the active sheet. It makes each<br />

chart an area chart by adjusting the ChartType property of the Chart object. A built-in constant,<br />

xlColumnClustered, represents a standard column chart.<br />

Sub ChartType()<br />

Dim ChtObj As ChartObject<br />

For Each ChtObj In ActiveSheet.ChartObjects<br />

ChtObj.Chart.ChartType = xlColumnClustered<br />

Next ChtObj<br />

End Sub<br />

The preceding example uses a For-Next loop to cycle through all the ChartObject objects on the active<br />

sheet. Within the loop, the chart type is assigned a new value, making it an area chart.<br />

765

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

Saved successfully!

Ooh no, something went wrong!