0

I am trying to calculate average, but i am getting an run-time error. Here is my code..

lastrowcell = Range("B1", Range("B1").End(xlDown)).Rows.Count
Range("F1").Value = "High+Low/2"
For n = 2 To lastrowcell
    Range(Cells(n, 6)).Formula = "=average(" & Range(Cells(n, 2), Cells(n, 3)).Address(False, False) & ")"
Next

Can anyone show what I did wrong.

Thanks in advance...

2
  • I think you need a Next n not just a Next. Commented Apr 19, 2016 at 5:41
  • No its not working... I am getting run-time error at Range(Cells(n, 6)).Formula = "=average(" & Range(Cells(n, 2), Cells(n, 3)).Address(False, False) & ")" Commented Apr 19, 2016 at 5:44

2 Answers 2

3

You don't need to loop, Excel is smart enough to fill the entire thing in one go:

lastrowcell = Range("B1", Range("B1").End(xlDown)).Rows.Count
Range("F1").Value = "High+Low/2"
Range("F6:F" & LastRow).Formula = "=AVERAGE(B6:C6)"

The 6 will be incremented in each row

If you want the last row though, its always better to come from the bottom up unless you are specifically looking for the first blank:

lastrowcell = Range("B" & Rows.Count).end(xlup).row
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I could help :)
1

Range(Cells(n, 6))

is not correct syntax for Range property. When there is only one parameter, it should be string. Instead you can use:

Cells(n, 6)

or

Range("F" & n).

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.