图表事件 - 激活工作表

时间:2014-06-09 10:00:24

标签: excel vba events charts

我使用以下代码识别图表的每个片段何时被选中,然后链接到不同的工作表:

Option Explicit

Public WithEvents CHT As Chart

Private Sub Workbook_Open()
Set CHT = ActiveSheet.ChartObjects(1).Chart
End Sub

Private Sub CHT_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long)
On Error GoTo Fin

If Range("A1") = "Product" Then
If Selection.Name = Range("J29").Value Then
    Application.Goto ActiveWorkbook.Sheets(Range("J29") & "P").Range("A1")
End If
If Selection.Name = Range("J30").Value Then
    Application.Goto ActiveWorkbook.Sheets(Range("J30") & "P").Range("A1")
End If
End If

If Range("A1") = "Country" Then
If Selection.Name = Range("J29").Value Then
    Application.Goto ActiveWorkbook.Sheets(Range("J29") & "C").Range("A1")
End If
If Selection.Name = Range("J30").Value Then
    Application.Goto ActiveWorkbook.Sheets(Range("J30") & "C").Range("A1")
End If
End If
Fin:
End Sub

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
If CHT Is Nothing Then
    Set CHT = ActiveSheet.ChartObjects(1).Chart
End If
End Sub

但是,这仅在工作簿的第一个工作表中选择任何图表段时才有效,并且无法识别其他工作表中任何图表段的选择。如何使其适用于所有工作表?我认为问题可能是GoTo命令没有激活链接的工作表,因此尝试添加以下代码:

If Selection.Name = Range("J29").Value Then
    Application.Goto ActiveWorkbook.Sheets(Range("J29") & "P").Range("A1")
    ActiveSheet.Activate
End If

不幸的是,这似乎也不起作用。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试使用Workbook_SheetActivate事件而不是SheetSelectionChange事件:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    If Sh.ChartObjects.Count > 0 Then Set CHT = Sh.ChartObjects(1).Chart
End Sub