获取图表数据点单元格引用

时间:2018-04-27 11:41:13

标签: excel excel-vba charts vba

我正试图从图表中获取一些基础数据。

我在下面循环遍历图表并可以访问数据点,例如标签的值等

Sub GetChartPoints()

  Dim mySrs As Series
  Dim iPts As Long
  Dim bLabeled As Boolean

  If ActiveChart Is Nothing Then
    MsgBox "Select a chart and try again.", vbExclamation
  Else
    For Each mySrs In ActiveChart.SeriesCollection
      bLabeled = False
      With mySrs
        For iPts = .Points.Count To 1 Step -1
            Debug.Print "w"
            Debug.Print mySrs.Points(iPts).HasDataLabel
            If mySrs.Points(iPts).HasDataLabel Then
                Debug.Print mySrs.Points(iPts).DataLabel.Text
                mySrs.Points(iPts).Interior.Color = RGB(0, 255, 0)
                Debug.Print mySrs.Values(iPts)
                Debug.Print mySrs.XValues(iPts)
            End If
        Next
      End With
    Next
  End If

End Sub

我想要做的是从基于此数据的数据中获取其他值,例如:如果数据点引用单元格C4我想要返回该数据(我的步骤将是获取值格式说E4等等。)

是否可以获取数据点指向的单元格

由于

1 个答案:

答案 0 :(得分:0)

你可以得到它,只需要添加一些Objects并获得一些狡猾的

请参阅下面的代码和附加部分(我在代码中标记了它)。

您可以保存一些对象和参数,我只想逐步展示完成的工作。

<强> 代码

Option Explicit

Sub GetChartPoints()

Dim mySrs As Series
Dim iPts As Long
Dim bLabeled As Boolean

If ActiveChart Is Nothing Then
    MsgBox "Select a chart and try again.", vbExclamation
Else
    For Each mySrs In ActiveChart.SeriesCollection
        bLabeled = False
        With mySrs
            For iPts = .Points.Count To 1 Step -1
                Debug.Print "w"
                Debug.Print mySrs.Points(iPts).HasDataLabel

                If mySrs.Points(iPts).HasDataLabel Then
                    Debug.Print mySrs.Points(iPts).DataLabel.Text
                    mySrs.Points(iPts).Interior.Color = RGB(0, 255, 0)
                    Debug.Print mySrs.Values(iPts)
                    Debug.Print mySrs.XValues(iPts)

                    ' ========= Addition start here =========
                    Dim RangeAddress As String, PointAddress As String
                    Dim SerValuesRng As Range, PointRng As Range

                    ' get the Range Address of the current series (Values)
                    RangeAddress = Split(mySrs.Formula, ",")(2)

                    ' set a Range object according to the result of the Address string
                    Set SerValuesRng = Range(RangeAddress)

                    ' Get the Cell location of current point in the Sereis range
                    Set PointRng = SerValuesRng.Cells(iPts)

                    ' Address of the PointRng
                    PointAddress = PointRng.Address(0, 0, xlA1, xlExternal)

                    ' for debug only
                    Debug.Print PointAddress
                    ' ========= Addition ends here =========

                End If
            Next
        End With
    Next
End If

End Sub