VBA从Excel图表中提取系列名称,X和Y值

时间:2016-03-07 16:33:47

标签: excel vba excel-vba charts

我一直在寻求从excel图表中提取数据的帮助。具体来说,我需要从图表上的所有点中提取系列名称 X Y 值。我从Excel的基本代码开始,但它只给了我X值。

Sub GetChartValues()
Dim NumberOfRows As Integer
Dim X As Object
Counter = 2

' Calculate the number of rows of data.
NumberOfRows = UBound(ActiveChart.SeriesCollection(1).Values)

Worksheets("ChartData").Cells(1, 1) = "X Values"

' Write x-axis values to worksheet.
With Worksheets("ChartData")
  .Range(.Cells(2, 1), _
  .Cells(NumberOfRows + 1, 1)) = _
  Application.Transpose(ActiveChart.SeriesCollection(1).XValues)
End With

' Loop through all series in the chart and write their values to
' the worksheet.
For Each X In ActiveChart.SeriesCollection
  Worksheets("ChartData").Cells(1, Counter) = X.Name

  With Worksheets("ChartData")
     .Range(.Cells(2, Counter), _
     .Cells(NumberOfRows + 1, Counter)) = _
     Application.Transpose(X.Values)
  End With

  Counter = Counter + 1
Next

End Sub

我需要弄清楚如何使这项工作,以便我可以创建给定值的表。我还附上了我正在制作的图表的图像。真的很感激任何帮助!

Chart Picture

Station Timetable Picture

1 个答案:

答案 0 :(得分:1)

开始使用,确保在运行代码之前选择了您的图表:

Sub Getting_data()

   Dim iSrs As Long
   Dim cht As Chart
   Dim srs As Series
   Dim wkst As Worksheet

   If ActiveChart Is Nothing Then Exit Sub

   Set cht = ActiveChart
   Set wkst = Worksheets.Add
   For iSrs = 1 To cht.SeriesCollection.Count
       Set srs = cht.SeriesCollection(iSrs)
       On Error Resume Next
       wkst.Cells(1, 2 * iSrs).value = srs.Name
       wkst.Cells(2, 2 * iSrs - 1).Resize(srs.Points.Count).value = _
           WorksheetFunction.Transpose(srs.XValues)
       wkst.Cells(2, 2 * iSrs).Resize(srs.Points.Count).value = _
           WorksheetFunction.Transpose(srs.Values)
   Next

End Sub