Extract data from MS Graph Chart
Problem
You want to extract the data behind an MSGraph chart. Since there might be more data in the underlying datasheet than is actually used, you want to extract only the data that's included in the chart.
Solution
This code will step through all the cells in a selected chart's datasheet (up to a limit you specify) and extract the data if it's included in the chart, ignore it if not.
Note: Assumes that you've first selected an MSGraph chart; includes no error-handling so if you don't do this, it'll break.
Sub ShowEnabledData()
' Object variables
Dim oGraphChart As Object
Dim oDatasheet As Object
Dim oSh As Shape
' Misc variables
Dim lCol As Long
Dim lRow As Long
Dim LastCol As Long
Dim LastRow As Long
Dim x As Long
Dim MaxRows As Long
Dim MaxColumns As Long
Set oSh = ActiveWindow.Selection.ShapeRange(1)
' The higher the number, the slower this gets
MaxRows = 100
MaxColumns = 20
Set oGraphChart = oSh.OLEFormat.Object
Set oDatasheet = oGraphChart.Application.DataSheet
With oDatasheet
' Find LastRow
For x = 1 To MaxRows
If .Rows(x).Include Then
LastRow = x
End If
Next x
' Find LastCol
For x = 1 To MaxColumns
If .Columns(x).Include Then
LastCol = x
End If
Next x
For lRow = 1 To LastRow
If .Rows(lRow).Include Then
Debug.Print .Cells(lRow, 1)
End If
Next lRow
' Supply column headings and set the columns to plot
For lCol = 1 To LastCol
If .Columns(lCol).Include Then
Debug.Print .Cells(1, lCol)
End If
Next lCol
' Fill in the data
For lCol = 2 To LastCol
For lRow = 2 To LastRow
If .Rows(lRow).Include And .Columns(lCol).Include Then
Debug.Print .Cells(lRow, lCol)
End If
Next lRow
Next lCol
End With ' oDataSheet
End Sub