简体   繁体   English

选择新数据时在Excel Graph上运行宏

[英]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. 因此,如果我在第一个选择上有4个值,而我在下一个选择中选择了7个值,那么最后我将第4个条形显示为红色。

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. 如果您将图表放在图表工作表中,则可以使用Chart_Select事件自动运行此代码。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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