我有一个子程序,可以根据表格中的系列更新图形。但是,表的第一行为空白,我想从我的系列集合中忽略该行。我想在我的数据主体范围内创建一个范围并使用它。这是我的代码:
Sub UpdateGraph()
Dim rng_pf As Variant, rng_bm As Variant, rng_date As Variant,
Dim lr as integer
' Defining ranges
With ThisWorkbook.Sheets("Time series")
lr = .ListObjects(1).ListColumns(1).Range.Rows.Count + 6 ' This corresponds to the last row in my table
rng_pf = .ListObjects(1).ListColumns("PF").DataBodyRange(2, lr) ' <-- This doesnt work
rng_bm = .ListObjects(1).ListColumns("BM").DataBodyRange(2, lr)
rng_date = .ListObjects(1).ListColumns("Date").DataBodyRange(2, lr)
End With
' Updating chart
With Sheets(1).ChartObjects("Chart 1").Chart
.FullSeriesCollection(1).Values = rng_pf
.FullSeriesCollection(2).Values = rng_bm
.FullSeriesCollection(1).XValues = rng_date
.FullSeriesCollection(2).XValues = rng_date
End With
End sub
我想到了创建一个基于databodyrange的数组,然后删除该数组的第一个元素,但这似乎是过分的。
运行代码时,我得到rng_pf为Empty
。
我的桌子:
答案 0 :(得分:1)
您应该更好地定义范围,但同时尝试一下吗?
Sub UpdateGraph()
Dim rng_pf As Range, rng_bm As Range, rng_date As Range
' Defining ranges
With ThisWorkbook.Sheets("Time series")
With .ListObjects(1)
With .ListColumns("PF")
Set rng_pf = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
End With
With .ListColumns("BM")
Set rng_bm = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
End With
With .ListColumns("Date")
Set rng_date = .DataBodyRange.Offset(1, 0).Resize(.DataBodyRange.Rows.Count - 1, 1)
End With
End With
End With
' Updating chart
With Sheets(1).ChartObjects("Chart 1").Chart
.FullSeriesCollection(1).Values = rng_pf
.FullSeriesCollection(2).Values = rng_bm
.FullSeriesCollection(1).XValues = rng_date
.FullSeriesCollection(2).XValues = rng_date
End With
End Sub
```vba
**EDIT:** minor code cleanup as per OP suggestion.