2016-08-16 41 views
0

我正在尋找一種更好(更漂亮)的方法來查找選定點的系列中的XValue。該點由用戶選擇(通過單擊),因此索引處於未知狀態。當前的方法循環遍歷每個點並比較名稱,這不太優雅,因爲理論上名稱在兩個不同點上可能是相同的。從點對象中查找XValue或Value

XValues是日期,有兩種類型的圖表。另外,系列名稱是在數據表中找到的日期,或者點XValue是在數據表中找到的日期。下面的代碼來自一個Class Module。當選擇圖表中的數據時,也應該選擇數據表中的相應行。

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 
+0

您是否可以包含設置說明的圖片並將這些圖片傳達給您的請求? –

+0

我不明白你的問題。這是不同之處在於增加了該事件的圖表的一個整個代碼:昏暗clsEventChart作爲新CEventChart 子InitEvents() 集clsEventChart.EvtChart = Summary.ChartObjects(「DynChart」)圖 結束子 – j74nilsson

+0

嘗試發佈您的問題[像這樣的答案](http://stackoverflow.com/a/38949184/3397819) –

回答

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行,如果選擇了其它的圖表元素(如軸),其避免運行時錯誤製成的小的修正。