简体   繁体   English

Excel VBA:使用带有动态范围的.formula

[英]Excel VBA: Using .formula with dynamic ranges

I'm trying to average some data sets which are in their own columns. 我正在尝试平均一些属于他们自己列的数据集。 The number of data sets may change, so the number of columns I average needs to be dynamic. 数据集的数量可能会发生变化,因此我平均需要的列数是动态的。

Also, I have multiple sets of data sets on each sheet, and because the data sets are dynamic, I add columns to the sheet earlier in the code, so I can't hardcode the starting point for the data set. 另外,我在每个工作表上都有多组数据集,并且因为数据集是动态的,所以我在代码的前面向工作表中添加了列,因此我无法对数据集的起点进行硬编码。 In other words, I can't just say... 换句话说,我不能只说...

Range("L5").formula = "=AVERAGE(H5:K5)"

... because I can't know for sure that the data sets start at H5. ...因为我无法确定数据集是从H5开始的。 It might start at F5, or G5, etc. 它可能从F5或G5等开始。

So I'm trying pass the a starting point as an argument in an As Range variable, but I don't know how interface this with a .formula. 所以我试图将起点作为As Range变量中的参数传递,但我不知道如何将它与.formula接口。

The following code doesn't work. 以下代码不起作用。 I'm guessing because I can't put a range variable in a string like this. 我猜是因为我不能将范围变量放在这样的字符串中。

Sub Average()
Dim c As Range

Set c = Range("B5:B10")

Range("F5").FormulaR1C1 = "=Average(" & c & ")"

Is there any way to use ranges with excel formulas like this? 有没有办法使用像这样的excel公式的范围?

它正在寻找地址,并且范围对象的默认值是:

Range("F5").Formula = "=Average(" & c.Address(0,0) & ")"

If the range to be averaged is the only data on the sheet, you can find the "last row" and "last column", then use those variables in the formula. 如果要平均的范围是工作表上的唯一数据,则可以找到“最后一行”和“最后一列”,然后在公式中使用这些变量。

To find last row: 要查找最后一行:

LastRow = Cells.Find("*", Range("A1"), xlFormulas, xlPart, _
        xlByRows, xlPrevious, False, False).Row

To find last column letter: 要查找最后一栏信:

LastCol = Split(Cells(1, ActiveSheet.Cells.Find(What:="*", _
    SearchDirection:=xlPrevious, _
    SearchOrder:=xlByColumns).Column).Address, "$")(1)

The formula in would change from: 公式将改为:

"=AVERAGE(H5:K5)"

to: 至:

"=AVERAGE(H5:" & LastCol & Last Row & ")"

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

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