Charting Techniques - VBA Macros
Sub Create_Chart()
Dim Sh As Worksheet
Set Sh = ActiveSheet
Dim chobj As ChartObject
With Range("D2:K16")
Set chobj = Sh.ChartObjects.Add( _
Height:=.Height, _
Top:=.Top, _
Left:=.Left, _
Width:=.Width)
End With
With chobj.Chart
.ChartType = xlColumnClustered
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = Sh.Range("B1").Value
'Define the Last row
Dim Lrow As Long
Lrow = Sh.Range("A" & Rows.Count).End(xlUp).Row
'Provide the values to the chart
.SeriesCollection(1).Values = Sh.Range("B2:B" & Lrow)
.SeriesCollection(1).XValues = Sh.Range("A2:A" & Lrow)
.SeriesCollection(1).Interior.ColorIndex = 3
.HasLegend = True
.Legend.Position = xlLegendPositionCorner
.HasTitle = True
.ChartTitle.Text = "Sales Report"
End With
chobj.Name = "Sales"
End Sub
Sub Delete_Chart_Object()
Sheet1.ChartObjects("Sales").Delete
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Dim Rng As Range
Set Rng = Range("A2:B100")
If Not Intersect(Target, Rng) Is Nothing Then
Dim Sh As Worksheet
Set Sh = ActiveSheet
Dim chobj As ChartObject
Set chobj = ChartObjects("Sales")
With chobj.Chart
Dim Lrow As Long
Lrow = Sh.Range("A" & Rows.Count).End(xlUp).Row
Dim S As SeriesCollection
.SeriesCollection(1).Values = Sh.Range("B2:B" & Lrow)
.SeriesCollection(1).XValues = Sh.Range("A2:A" & Lrow)
.SeriesCollection(1).Interior.ColorIndex = 3
End With
End If
End Sub