我有一个代码将范围复制到某个单元格并将数据源更改为图表。图表具有组合图表类型,其具有堆叠列,xlLineMarker
具有最后一个系列(总计)。系列集的数量因用户选择(2或更多)而异。
它可以工作,但有时候图表没有像附加的图像那样完全更新(显示系列名称为'series1,series2,...的空图表)。当它发生时,右键单击图表并单击选择数据,然后只需选择除系列1以外的任何系列更新图表。不刷新或重新分配数据源。只需在数据选择窗口中选择'series2'或其他,然后点击'取消',我怀疑宏没有完全执行...,
我做错了什么?或者有没有办法完全更新图表?Sub chtupdate()
Dim rng As Range
Dim i As Integer
Dim n As Integer
Set rng = Range("G37").CurrentRegion
ActiveSheet.ChartObjects("Chart1").Activate
With ActiveChart
.ChartArea.ClearContents
.SetSourceData Source:=rng, PlotBy:=xlRows
n = ActiveSheet.ChartObjects(1).Chart.SeriesCollection.Count
For i = 1 To n - 1
.SeriesCollection(i).ChartType = xlColumnStacked
Next i
.SeriesCollection(n).ChartType = xlLineMarkers
End With
End Sub
答案 0 :(得分:0)
尝试下面的代码,我添加了ChartObject
和Series
个对象变量,以获得更简单,更“干净”的代码。此外,为了避免使用ActiveSheet
和ActiveChart
- 一种不可靠的方法。
<强>代码强>
Option Explicit
Sub chtupdate()
Dim MyCht As ChartObject
Dim Ser As Series
Dim Rng As Range
Dim i As Long
Dim n As Long
' fully qualify all your Ranges and Cells
With Worksheets("Sheet3") ' <-- replace "Sheet1| with your sheet's name
Set Rng = .Range("G37").CurrentRegion
' set the chart object
Set MyCht = .ChartObjects("Chart1")
End With
With MyCht
.Chart.ChartArea.ClearContents
.Chart.SetSourceData Source:=Rng, PlotBy:=xlRows
For Each Ser In .Chart.SeriesCollection
Ser.ChartType = xlColumnStacked
Next Ser
' modify the last one
Set Ser = .Chart.SeriesCollection(.Chart.SeriesCollection.Count)
Ser.ChartType = xlLineMarkers
End With
End Sub