Reputation: 187
I am looking for a way to reference active/selected chart data point in Excel using VBA.
Imagine I have a line chart, which I would like to add an error bar to. But, I do not want to add error bars to the whole series, but only to ONE, selected point. See the screen below:
What I want to do is to add a vertical error bar that would point down to the X-axis, something like this:
I KNOW how to do it in Excel, there are multiple ways, for example, adding a new one-point series and then adding an error bar. There are other ways. The issue I have is HOW to reference active/selected data point.
If I would choose to create a new, one point series, I need to know the point number to do that. I know (I used it) that you can reference points with Points object/method. Sadly, I do not know how to extract the selected point number, coordinates, whatever, so I can work with it later on in my project.
I cannot add any code, as everything I have done is formatting and playing with error bars, as well as iterating through existing, ALL data points (the code would have no use in this case). What I am looking for is THE selected point information, so I could refer to it as .Point(x) with x being my previously extracted point number, without being forced to reference point number right away like .Point(8) (I do not know the specific number, as I just clicked on it).
I have seen the way to extract it using chart events, but this is a an overkill for what I want to do in my little simple project (especially how to reference the "extracted" point in other macros, outside the class module).
Any ideas? All help is greatly appreciated, as I am lost after 3 days of trying to find the way to reference it.
Upvotes: 1
Views: 2064
Reputation: 49998
To get the index, you can parse the point's Name
, which is in the format:
S<series number>P<point number>
Sub Test()
If TypeOf Selection Is Point Then
Dim p as Point
Set p = Selection
Debug.Print CLng(Split(p.Name, "P")(1)) ' this is p's index
End If
End Sub
To get more information about that point, such as the x and y values, perhaps you could do the following:
Sub Test()
If TypeOf Selection Is Point Then
Dim p As Point
Set p = Selection
Dim i As Long
i = CLng(Split(p.Name, "P")(1))
Dim s As Series
Set s = p.Parent
Debug.Print s.Values(i) ' Values is a one-based array so you can use the point index to get its corresponding value
Debug.Print s.XValues(i)
End If
End Sub
Upvotes: 3