单击DataLabel对象时触发事件

时间:2018-03-29 17:52:49

标签: vba excel-vba excel

当我点击ActiveChart中的DataLabel对象时,我正试图在Excel宏中触发事件。我无法使用SheetChange事件,因为更改发生在图表中。它可能很简单,但我很难获得正确的语法来触发这种事件。谢谢!

1 个答案:

答案 0 :(得分:0)

这实际上非常棘手!如果图表位于单独的图表表格中会更容易,但我从未真正使用其中一个。 Jon Peltier有更长的演练here,但这是它的要点:

  1. 创建一个名为" ChartClass"的新类模块。把它放进去吧:

    Public WithEvents chartThing As Chart
    Private Sub chartThing_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long)
    
        Dim paramType As String
        paramType = TypeName(Selection)
    
        If paramType = "DataLabel" Or paramType = "DataLabels" Then
            'Do whatever you want
            MsgBox "You've selected some labels"
        End If
    
    End Sub
    
  2. 将其放入标准模块中:

    Dim chartThings() As New ChartClass
    Sub setCharts()
    
        Dim ws As Worksheet
        Dim chartCount As Long
        Set ws = ActiveSheet
        chartCount = ws.ChartObjects.Count
    
        If chartCount > 0 Then
            ReDim chartThings(1 To chartCount)
            Dim i As Long
            For i = 1 To chartCount
                Set chartThings(i).chartThing = ws.ChartObjects(i).Chart
            Next
        End If
    
    End Sub
    
  3. 将此Worksheet_Activate事件添加到包含图表的工作表中:

    Private Sub Worksheet_Activate()
    
        Call setCharts
    
    End Sub