Friday, February 2, 2018

Create a dynamic chart automatically and change it's value dynamically when the original data is filtered or sorted using VBA,VBA Teacher Sourav,Kolkata 09748184075

Sub Macro1()

Dim ch As Shape

    Range("B13").Select
    Selection.CurrentRegion.Select
    ActiveSheet.Shapes.AddChart.Select
  
    Set ch = ActiveSheet.Shapes(1)
    ch.Name = "Chart 3"
    ActiveChart.ChartType = xlColumnClustered
    ActiveChart.SetSourceData Source:=Range("'(2)'!$B$12:$C$36")
    ActiveChart.Legend.Select
    Selection.Delete
    ActiveSheet.ChartObjects("Chart 3").Activate
    ActiveChart.PlotArea.Select
    ActiveChart.Axes(xlValue).MajorGridlines.Select
    Selection.Delete
    ch.Placement = xlFreeFloating
    Range("B13").Select
    Selection.AutoFilter
    ActiveSheet.Range("$B$12:$C$36").AutoFilter Field:=2, Criteria1:="5", _
        Operator:=xlTop10Items
    ActiveSheet.ChartObjects("Chart 3").Activate
    ActiveChart.Axes(xlCategory).Select
    ActiveChart.Axes(xlCategory).CategoryType = xlCategoryScale
    Range("C19").Select
    ActiveWorkbook.Worksheets("(2)").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("(2)").AutoFilter.Sort.SortFields.Add Key:=Range( _
        "C19"), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("(2)").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    ActiveSheet.ChartObjects("Chart 3").Activate
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.SeriesCollection(1).ApplyDataLabels
    ActiveChart.SeriesCollection(1).DataLabels.Select
    ActiveChart.SeriesCollection(1).Select
    ActiveChart.ChartGroups(1).VaryByCategories = True
End Sub

No comments:

Post a Comment