简体   繁体   中英

Run macro on Excel Graph when I select new data

Like the title says, I want to be able to automatically run my macro whenever I select a series for the graph. I need the last bar to be colored red, and I can do that with my macro, but when I select a new series of data, the red bar is the last bar of the previous data selection. So if I have 4 values on the first selection, and I pick 7 values for the next selection, I end up having the 4th bar in red.

This is the macro I use

Sub CustomChartMacro() 
Application.ScreenUpdating = True 
Dim w As Worksheet 
Dim chtSeries As Excel.Series 
Dim i As Long 
Dim a As Long 

    'Call CustomChartMacro a = ActiveChart.SeriesCollection(1).Points.Count * ActiveChart.SeriesCollection.Count 

   For Each chtSeries In ActiveChart.SeriesCollection


     With chtSeries
            For i = a To .Points.Count

                If .Values(i) = a Then
                    .Points(i).Interior.Color = RGB(204, 9, 47)
                Else
                    .Points(i).Interior.Color = RGB(89, 89, 91)
                End If
            Next i


    End With 

 Next chtSeries

 End Sub

Thank you for your suggestions.

UPDATE

You can automate this code to run if you have your chart in a chart sheet, by using the Chart_Select event. The code will fire each time you click on a series in your chart.

Right-click on the Chart Sheet Tab Name and select view code and copy this module for the chart sheet:

Private Sub Chart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long)

 If ElementID = xlSeries Then CustomChartMacro

End Sub

How about the below code. It will check if the point is the last point in the series and set it's color to red, otherwise it will set all colors to black.

Sub CustomChartMacro()

Application.ScreenUpdating = True
Dim w As Worksheet
Dim chtSeries As Excel.Series
Dim i As Long
Dim a As Long

For Each chtSeries In ActiveChart.SeriesCollection

    With chtSeries

        a = .Points.Count

        For i = 1 To a

            If i = a Then

                .Points(i).Interior.Color = RGB(204, 9, 47)

            Else

                 .Points(i).Interior.Color = RGB(89, 89, 91)

            End If

        Next i


    End With

Next chtSeries

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM