如何在excel中自动更新图表

我有一个macros,运行一个生成一个新的工作表和填充各种graphics。 这些图表的数据来自sheet2。 我希望能够在生成图表后删除图表2,而不会丢失图表中的所有信息。 到目前为止,我已经尝试将计算设置为手动,保护工作表,并使用ProtectData和ProtectSelection方法保护图表。 以上所有都失败了。 有什么办法使用vba来阻止图表生成后更改? 谢谢。

编辑:答案build议使用范围内的值填充数组,然后使用该数组生成图表。 现在我试图生成图表时遇到types不匹配错误。 是否有可能将源数据设置为一个数组? 这是我的代码到目前为止:

Dim PlotRangeBar() As Long Dim PlotRangePie As Variant Dim XValPie As Variant Dim XRangeBar As Range Dim CellCount As Long 'Create bar graph Set XRangeBar = ActiveWorkbook.Sheets(2).Range("B" & DataStart & ":B" & DataEnd) i = 0 For Row = DataStart To DataEnd If Cells(Row, UsedColTimesheet).FormulaR1C1 <> "0" And Cells(Row, UsedColTimesheet) <> vbNullString Then ReDim Preserve PlotRangeBar(i) PlotRangeBar(i) = Cells(Row, UsedColTimesheet).Value i = i + 1 End If Next ActiveWorkbook.Sheets(Sheets.Count).Select ActiveSheet.Shapes.AddChart.Select With ActiveChart .ChartType = xlColumnStacked .SetSourceData Source:=PlotRangeBar .SeriesCollection.NewSeries .SeriesCollection(1).XValues = XRangeBar .SetElement (msoElementChartTitleCenteredOverlay) .ApplyLayout (1) .ChartTitle.Text = ResourceName & " - Hours per project" .Legend.Delete .ChartStyle = 18 .ProtectSelection = True End With 

将数据加载到数组中,并在创build数组时使用这些数组加载图表。