Charting Techniques - VBA Macros

     

    Create Dynamic Chart using CHANGE EVENT of worksheet object in excel workbook

     

    Download The Coding Workbook

     

     

    Sub Create_Chart()

    'Define Worksheet
    Dim Sh As Worksheet
    Set Sh = ActiveSheet

    'Define chart Object
    Dim chobj As ChartObject

    'Provide measurements to the chart object
    With Range("D2:K16")
    Set chobj = Sh.ChartObjects.Add( _
    Height:=.Height, _
    Top:=.Top, _
    Left:=.Left, _
    Width:=.Width)
    End With

    With chobj.Chart
    'Provide the chart type
    .ChartType = xlColumnClustered
    'Add the new series to the chart
    .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
    'Provide the name for the chart
    chobj.Name = "Sales"
    End Sub





    Sub Delete_Chart_Object()
    Sheet1.ChartObjects("Sales").Delete
    End Sub







    Change Event of Worksheet Object Code:

    Private Sub Worksheet_Change(ByVal Target As Range)


    'Define the 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