获取Excel图表数据源

时间:2016-11-15 22:14:51

标签: excel vb.net visual-studio charts excel-charts

使用Visual Studio轻松设置Excel图表的数据源,如

Chart.SetSourceData(Source:=SomeRange)

但是如何获取(检索)Excel文件中已存在的图表的数据源(范围)?

3 个答案:

答案 0 :(得分:0)

我认为它已经在这里解决了: Excel VBA - 获取图表数据范围 https://stackoverflow.com/a/28391220/6868389

答案 1 :(得分:0)

这是一个解析系列中范围的函数。如果你有不使用范围的自定义系列公式,它可能会破坏。

Public Function GetSourceData(ByRef cht As Chart) As Range

    Dim srs As Series
    Dim vaArgs As Variant
    Dim i As Long
    Dim rReturn As Range

    For Each srs In cht.SeriesCollection
        vaArgs = Split(Split(srs.Formula, "SERIES(")(1), ",")
        For i = 0 To UBound(vaArgs) - 1
            If rReturn Is Nothing Then
                Set rReturn = Range(vaArgs(i))
            Else
                Set rReturn = Union(rReturn, Range(vaArgs(i)))
            End If
        Next i
    Next srs

    Set GetSourceData = rReturn

End Function

用作:

?getsourcedata(activechart).Address
$B$2:$C$2,$A$3:$C$14

答案 2 :(得分:0)

Visual Studio代码如下所示:

Dim g As String
Dim gg() As String
Dim a As Excel.ChartObject

    a = Globals.ThisAddIn.Application.ActiveSheet.chartobjects(1)
    g = a.Chart.SeriesCollection(1).formula
    gg = g.Split(",")

    MsgBox(gg(2))