Listing Creating a Chart Using the Chart Object

' creates a chart using basic Chart properties and methods Sub CreateExamp1eChartVersionII() Dim ws As Worksheet Dim rgChartData As Range Dim chrt As Chart

Set ws = ThisWorkbook.Worksheets("Basic Chart") Set rgChartData = ws.Range("B1").CurrentRegion

' create a new empty chart Set chrt = Charts.Add

' embed chart in worksheet—this creates a new object Set chrt = chrt.Location(x1LocationAsObject, ws.Name)

With chrt

.SetSourceData rgChartData, xlColumns .HasTitle = True

.ChartTitle.Caption = "Gross Domestic Product Version II" .ChartType = xlColumnClustered

With .Axes(xlCategory) .HasTitle = True .AxisTitle.Caption = "Year" End With

With .Axes(xlValue) .HasTitle = True

.AxisTitle.Caption = "GDP in billions of $" End With

End With

Set chrt = Nothing Set rgChartData = Nothing Set ws = Nothing End Sub

As you can see in Figure 10.17, this listing produces the same result as Listing 10.9. Personally, I prefer this listing over the ChartWizard method. You have more flexibility doing it manually as we do here, and I think it's easier to read and understand.

Figure 10.17

An exact match. This is the chart produced by Listing 10.10.

Figure 10.17

An exact match. This is the chart produced by Listing 10.10.

0 0

Post a comment