根据 VBA 中的可变单元格范围设置图表源数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14388270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 14:45:09  来源:igfitidea点击:

Setting a chart source data based on a variable cell range in VBA

excelvbaexcel-vbacharts

提问by Ahmad A Hammoudi

I am creating a report template part of which will be generating data charts with a structure similar to a moving average

我正在创建一个报告模板部分,其中将生成结构类似于移动平均线的数据图表

for this I need to select a range of data in one sheet (e.g. f10:i14) and place and set it as the source of one chart

为此,我需要在一张纸(例如f10:i14)中选择一系列数据并将其放置并将其设置为一个图表的来源

The following piece of code works

下面的一段代码有效

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range("f10,i14")

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range("f10,i14")

but this does not

但这不

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range(Cells(x, y), Cells(k, z))

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range(Cells(x, y), Cells(k, z))

it returns a 1004 error

它返回一个 1004 error

But I need to specify the range based on variable indices for my report purposes, please help

但是为了我的报告目的,我需要根据变量索引指定范围,请帮助

回答by Siddharth Rout

You have to fully qualify the .Cellsobject

您必须完全限定.Cells对象

Try this

尝试这个

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range(Sheets("Weekly Trends").Cells(x, y), Sheets("Weekly Trends").Cells(k, Z))

ActiveChart.SetSourceData Source:=Sheets("Weekly Trends").Range(Sheets("Weekly Trends").Cells(x, y), Sheets("Weekly Trends").Cells(k, Z))

You can also make the above code short

您也可以使上面的代码简短

With Sheets("Weekly Trends")
    ActiveChart.SetSourceData Source:=.Range(.Cells(x, y), .Cells(k, Z))
End With