如何在VBA中获得系列的x和y范围?
然后,VBA代码应如下所示:
Sub Getxyrng(ch as chart)
Dim ser As series
Dim xrng As Range
Dim yrng As Range
Set ser = ch.SeriesCollection(1) ' the series with a x- and y-range already referenced
Set xrng = ser.xvalues 'this doesn't work
Set yrng = ser.Values 'what would the code need to look like in order to return a range?
End Sub
所以问题是,系列类型的哪个属性是包含该系列源数据的x- / y范围。如果您手动更改范围,它看起来像这样:< / p>
因此可以手动访问,例如:左键单击>选择数据>编辑
这意味着必须有一个保存这些范围引用的属性。
答案 0 :(得分:2)
这些路线对您有用吗?
Sub GetSourceCellsAddress()
Dim MyArr() As String
Dim xrng As Range, yrng As Range
MyArr() = Split(ActiveSheet.ChartObjects(1).Chart.SeriesCollection(1).Formula, ",")
Set yrng = Range(MyArr(UBound(MyArr) - 1))
Set xrng = Range(MyArr(UBound(MyArr) - 2))
End Sub
输入:
输出:
答案 1 :(得分:1)
好的,我承认。我对解决方案不是很自豪,但是它确实起作用。正如问题注释中已经指出的那样,解决此问题的一种方法是解析.formula
属性。需要注意的一点是,系列标题可以包含逗号,因此解决方案首先过滤到最后一个符号,然后使用逗号作为分隔符。
Private Function GetSerRng(ser As series, Xval As Boolean) As Range
Dim f As String
Dim i As Integer
Dim parts As New Collection
f = ser.Formula
' filter "
For i = 1 To 2
f = Right(f, Len(f) - InStr(1, f, """"))
Next i
' split by ,
While InStr(f, ",") <> 0
parts.Add Replace(Left(f, InStr(2, f, ",")), ",", vbNullString)
f = Right(f, Len(f) - InStr(2, f, ","))
Wend
' set Range
If Xval Then
Set GetSerRng = Range(parts(1))
Else
Set GetSerRng = Range(parts(2))
End If
End Function
这不是最优雅的解决方案,但它可以工作。