将系列集合设置为范围 - VBA - Excel

时间:2017-04-30 22:11:23

标签: excel-vba vba excel

我有一个带有收藏系列的图表。我想将收集系列的范围向右扩展一列。以下代码有效。但是,它假定我知道集合系列的范围(下例中的“B36:DA36”)。事实上,我希望收集系列的初始范围(在调整大小之前)以动态的方式定义,因为它每天都在变化,并且如下定义它将无法完成工作。

Sub resize_collection_series()

Dim NumRows As Long
Dim NumCols As Long
Dim Rng As Range

Set Rng = Range("B36:DA36")

NumRows = Rng.Rows.Count
NumCols = Rng.Columns.Count

Worksheets("Sheet1").Activate
ActiveSheet.ChartObjects("Chart 6").Activate
ActiveChart.SeriesCollection(1).Select
ActiveChart.SeriesCollection(1).Values = Rng.Resize(, NumCols + 1)
ActiveChart.SeriesCollection(1).XValues = Rng.Resize(, NumCols + 1)
End Sub

我没有成功地尝试了这样的事情:

Set Rng = Worksheets("Sheet1").ChartObjects("Chart 6").SeriesCollection(1)
Set Rng = Worksheets("Sheet1").ChartObjects("Chart 6").SeriesCollection(1).Values

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

尝试以下代码设置"图表6" SeriesCollection(1)动态地显示第12行的现有列数(根据您的评论)。

<强>代码

Option Explicit

Sub resize_collection_series()

Dim NumRows As Long
Dim NumCols As Long
Dim Rng As Range
Dim LastCol As Long

Dim MyCht As ChartObject
Dim Ser As Series

' get dynamic last column at row 12
LastCol = Cells(12, Columns.Count).End(xlToLeft).Column

' set the Range dynamic
Set Rng = Range(Cells(12, 1), Cells(12, LastCol))

' set "Chart 6" to MyCht Variable
Set MyCht = Worksheets("Sheet1").ChartObjects("Chart 6")
With MyCht
    Set Ser = .Chart.SeriesCollection(1)
    With Ser
        .Values = "=" & Rng.Address(False, False, xlA1, xlExternal)

    End With
End With

End Sub