2

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?

2 Answers 2

4

It is looking for the address and the default of a range object is value:

Range("F5").Formula = "=Average(" & c.Address(0,0) & ")"
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.