Finding data range reference for a series in chart using vba
Hello,
Is it possible to use VBA to identify the range reference for a series on a chart?
For example I have a chart object called "Unemployment & Inflation Rate " and it has a SeriesCollection(1) in it. I want to find out what range series collection one is referencing. So if its K4:K100, I want to show this say in a msg box.
So I guess macro would read something like this:
Code:
sub Test
ActiveSheet.ChartObjects("Unemployment & Inflation Rate ").select
ActiveChart.SeriesCollection(1).Select
'code here to read of the data range the series is referencing
'e.g reference = xxxxxxxxxxx
msgbox reference
End Sub
Could this be done?
Thanks,
Lucas
Loop through all charts in book
I know this post is old, but just used it with slight modification (John Walkenbach's code mentioned above):
Small addition to loop through several charts. My charts had external links, so print.debugged the full formula to catch the full link, including the external source name.
Sub Chartlist()
Dim wks As Worksheet
Dim lngS As Long, lngC As Long, lngX As Long, chrs As ChartObject
For lngS = 1 To ActiveWorkbook.Sheets.Count
With ActiveWorkbook.Sheets(lngS)
For lngC = 1 To .ChartObjects.Count
lngX = lngX + 1
Set chrs = .ChartObjects(lngC)
chrs.Activate
test (lngC)
Set chrs = Nothing
Next lngC
End With
Next lngS
End Sub
Sub test(nbr As Long)
Dim mychart As Chart
Set mychart = ActiveSheet.ChartObjects(nbr).Chart
Set DataRange = GetChartRange(mychart, 1, "values")
Debug.Print mychart.name & ": " & ActiveSheet.name & "-" & DataRange.Address
End Sub
Function GetChartRange(cht As Chart, series As Integer, _
ValOrX As String) As Range
'cht: A Chart object
'series: Integer representing the Series
'ValOrX: String, either "values" or "xvalues"
Dim Sf As String, CommaCnt As Integer, Commas() As Integer, ListSep As String * 1, Temp As String, i As Integer
Set GetChartRange = Nothing
On Error Resume Next
'Get the SERIES formula
Sf = cht.SeriesCollection(series).Formula
Debug.Print Sf
'Check for noncontiguous ranges by counting commas
'Also, store the character position of the commas
CommaCnt = 0
ListSep = Application.International(xlListSeparator)
For i = 1 To Len(Sf)
If Mid(Sf, i, 1) = ListSep Then
CommaCnt = CommaCnt + 1
ReDim Preserve Commas(CommaCnt)
Commas(CommaCnt) = i
End If
Next i
If CommaCnt > 3 Then Exit Function
'XValues or Values?
Select Case UCase(ValOrX)
Case "XVALUES"
'Text between 1st and 2nd commas in SERIES Formula
Temp = Mid(Sf, Commas(1) + 1, Commas(2) - _
Commas(1) - 1)
Set GetChartRange = Range(Temp)
Case "VALUES"
'Text between the 2nd and 3rd commas in SERIES Formula
Temp = Mid(Sf, Commas(2) + 1, Commas(3) - _
Commas(2) - 1)
Set GetChartRange = Range(Temp)
End Select
End Function