Set a Chart series source to a named range via Macro

删除回忆录丶 提交于 2020-01-03 05:46:30

问题


I have a sheet with a existing chart and the proper dynamic named ranges to feed that chart the right data.

My problem comes that the sheet is a template that is copied and the copies' charts don't point to the named ranges anymore. The named ranges get copied to the sheet (the ranges are sheet specific) so it seems like it should be a matter of just updating the series source data. Good old record gave me the following syntax when I recorded doing that manually:

ActiveChart.SeriesCollection(1).XValues = "=='Risk 1'!PDates"
ActiveChart.SeriesCollection(1).Values = "=='Risk 1'!Plan"
ActiveChart.SeriesCollection(2).XValues = "=='Risk 1'!ADates"
ActiveChart.SeriesCollection(2).Values = "=='Risk 1'!Actuals"

I've attempted to reset them to the named ranges with a modified version of that:

For Each Cht In TempSheet.ChartObjects
    'Series 1 is the Plan
    Cht.Activate 
    ActiveChart.SeriesCollection(1).XValues = "=='" & TempSheet.Name & "'!PDates"
    ActiveChart.SeriesCollection(1).Values = "=='" & TempSheet.Name & "'!Plan"

    'Series 2 is the Actuals
    ActiveChart.SeriesCollection(2).XValues = "=='" & TempSheet.Name & "'!ADates"
    ActiveChart.SeriesCollection(2).Values = "=='" & TempSheet.Name & "'!Actuals"
Next

I hit an error, "Application-defined or object-defined error", at the statement that tries to update the X Values for the first series.

I've also tried adding the PlotArea select statement in, just in case that was the issue, but that didn't fix the problem. I checked that the statements the collections are supposed to be getting set to evaluate correctly (ex. "=='" & TempSheet.Name & "'!PDates" evaluates to "=='Risk 1'!PDates", which is what the series should be pointed at).

With that, I'm fairly well stumped and would appreciate any help anyone could provide. Thanks in advance!


回答1:


Rather than using a string that tries to be a range, try a real range and then get its values:

ActiveChart.SeriesCollection(1).XValues = TempSheet.Range("PDates").Value

(etc)




回答2:


If the "template" worksheet has the data and chart the way you want, but with dummy data, save it as an official Excel template. Then when you need one of these sheets, right click on a sheet tab and click Insert... Select the template in the dialog and click OK. When this sheet is inserted based on the template, its chart will be linked to the Names in the sheet.



来源:https://stackoverflow.com/questions/25412351/set-a-chart-series-source-to-a-named-range-via-macro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!