简体   繁体   中英

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. It might start at F5, or G5, etc.

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.

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?

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

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 & ")"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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