从点对象中查找XValue或Value

时间:2016-08-16 08:17:18

标签: excel excel-vba vba

我正在寻找一种更好(更漂亮)的方式来找出一个选定点的系列中的XValue。该点由用户选择(通过点击),因此索引未知。当前方法循环遍历每个点并比较不太优雅的名称,因为理论上两个不同点的名称可以相同。

XValues是日期,有两种类型的图表。系列名称是在数据表中找到的日期,或者点XValue是在数据表中找到的日期。以下代码来自课程模块。选择图表中的数据时,还应选择数据表中的相应行。

Option Explicit
' Declare object of type "Chart" with events
Public WithEvents EvtChart As Chart
Private Sub EvtChart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long)
    Dim d As Date, r As Range
    If TypeOf Selection Is Series And IsDate(Selection.Name) Then
        d = CDate(Selection.Name)
    ElseIf TypeOf Selection Is Point Then
        If IsDate(Selection.Parent.Name) Then
            d = CDate(Selection.Parent.Name)
        Else
            Dim s As Series, p As Point, i As Long
            Set s = Selection.Parent
            Set p = Selection
            For i = 1 To s.Points.Count
                If p.Name = s.Points(i).Name Then
                    d = s.XValues(i)
                    Exit For
                End If
            Next
        End If
    Else
        Exit Sub
    End If
    Set r = Range(Summary.Cells(HROW + 2, 1), Summary.Cells(1048576, 1).End(xlUp)).Find(d, , xlFormulas)
    If Not r Is Nothing Then r.EntireRow.Select
End Sub

1 个答案:

答案 0 :(得分:0)

正如@alexricher在评论中指出的那样,Arg2给出了所需的索引。修改后的代码如下所示:

Option Explicit
' Declare object of type "Chart" with events
Public WithEvents EvtChart As Chart
Private Sub EvtChart_Select(ByVal ElementID As Long, ByVal Arg1 As Long, ByVal Arg2 As Long)
    Dim d As Date, r As Range
    If TypeOf Selection Is Series Then
        If IsDate(Selection.Name) Then d = CDate(Selection.Name)
    ElseIf TypeOf Selection Is Point Then
        If IsDate(Selection.Parent.Name) Then
            d = CDate(Selection.Parent.Name)
        Else
            Dim s As Series
            Set s = Selection.Parent
            d = s.XValues(Arg2)
        End If
    Else
        Exit Sub
    End If
    Set r = Range(Summary.Cells(HROW + 2, 1), Summary.Cells(1048576, 1).End(xlUp)).Find(d, , xlFormulas)
    If Not r Is Nothing Then r.EntireRow.Select
End Sub

我还在If TypeOf Selection Is Series Then行中做了一个小的修正,如果选择了另一个图表元素(例如轴),则会避免运行时错误。

相关问题