获取 Excel 个图表数据源
Get Excel Chart datasource
使用 Visual Studio 为 Excel 图表设置数据源很容易,例如
Chart.SetSourceData(Source:=SomeRange)
但是如何获取(检索)Excel 文件中已存在图表的数据源(范围)?
我想这里已经解决了:
Excel VBA - 获取图表数据范围
这是一个函数,可以解析系列之外的范围。如果您有不使用范围的自定义系列公式,它可能会中断。
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:$C,$A:$C
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))
使用 Visual Studio 为 Excel 图表设置数据源很容易,例如
Chart.SetSourceData(Source:=SomeRange)
但是如何获取(检索)Excel 文件中已存在图表的数据源(范围)?
我想这里已经解决了:
Excel VBA - 获取图表数据范围
这是一个函数,可以解析系列之外的范围。如果您有不使用范围的自定义系列公式,它可能会中断。
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:$C,$A:$C
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))