简体   繁体   English

Excel中的VBA:使用动态范围控制图表

[英]VBA in Excel: Controlling a Chart with Dynamic Ranges

I have been working on an excel model with dynamic charts. 我一直在研究带有动态图表的Excel模型。 Essentially a user should be able to change the periods charted on a diagram - so fairly simple. 本质上,用户应该能够更改图表上绘制的周期-非常简单。 However, I keep having issues with making the VBA work as I intend (I do not get errors, but it does not behave as I would expect). 但是,我在使VBA正常工作方面一直存在问题(我没有收到错误,但是没有达到我的预期)。 What I am attempting to do: 我正在尝试做的是:

  1. Set a dynamic legend (depending on how many items the user wants to chart) - the number of items is defined in Excel and is simply added to the number of rows in VBA. 设置动态图例(取决于用户要绘制的项目数量)-项目的数量在Excel中定义,并简单地添加到VBA中的行数中。
  2. Set a dynamic range (start and end depends on user input), however, it seems like I cannot define where the range containing data for plotting starts. 设置一个动态范围(开始和结束取决于用户输入),但是,似乎无法定义包含绘图数据的范围的开始位置。

In my code below Excel seems to ignore the parameters in Rng2 , ie it starts plotting from column 53 until column 77, instead of what I intend being from column 77 to 89. Alternatively if I replace the content of Rng3 with hardcoded references it works just fine (ie Rng3 = .Range("$AZ5662:$AZ5667,$BY$5662:$CJ$5667") ). 在我下面的代码中,Excel似乎忽略了Rng2的参数,即它从53列开始绘制到77列,而不是我打算从77列绘制到89列。或者,如果我将Rng3的内容替换为硬编码的引用,它就可以正常工作罚款(例如Rng3 = .Range("$AZ5662:$AZ5667,$BY$5662:$CJ$5667") )。

What is wrong? 怎么了?

Thank you very much! 非常感谢你!

Best regards, Philip 最好的问候,菲利普

Set Cht = .ChartObjects("Chart 14").Chart
Set Rng1 = .Range(Cells(5662, 52), Cells(5663 + Worksheets("Control").Range("F20"), 52))
Set Rng2 = .Range(Cells(5662, 77), Cells(5663 + Worksheets("Control").Range("F20"), 88))
Set Rng3 = .Range(Rng1, Rng2)
Cht.SetSourceData _
Source:=Rng3
Cht.PlotBy = xlRows

When you use Range(Range1,Range2) , it fetches the upper-left cell of Range1 , and the lower-right cell of Range2 to build a range. 当您使用Range(Range1,Range2) ,它将获取Range1的左上方单元格和Range2的右下方单元格以构建范围。

Therefore the result of your Rng3 is a square starts from Cells(5662,52) and ends at Cells(5663+X,88) , which is not you wanted. 因此,Rng3的结果是一个从Cells(5662,52)并在Cells(5663+X,88)处结束的正方形,这不是您想要的。

You can try another method called Union( Rng1 , Rng2 , .... ) 您可以尝试另一个称为Union( Rng1 , Rng2 , .... )

It will store all the boundaries of each Range object given, so it can be several separated areas, or even an odd shape such as a heart or something :P 它将存储给定的每个Range对象的所有边界,因此它可以是几个单独的区域,甚至可以是一个奇怪的形状,例如心脏或其他东西:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM