VBA- Loop thru a range of ranges to get an average.

farmerscott

Well-known Member
Joined
Jan 26, 2013
Messages
819
Office Version
  1. 365
Platform
  1. Windows
Hi Everybody,

As per the code below, I have 4 ranges. I would like to find a way to loop thru them, so I can get an average of each.

The code is erroring- as marked.

VBA Code:
Set rng2 = ws.Range("B1:B" & (f - 1))
Set rng3 = ws.Range("B" & f & ":B" & (g - 1))
Set rng4 = ws.Range("B" & g & ":B" & (h - 1))
Set rng5 = ws.Range("B" & h & ":B" & lr)


For i = 1 To 4 Step 1
rng = WorksheetFunction.Choose(i, rng2, rng3, rng4, rng5)

x = WorksheetFunction.Average(rng) [COLOR=rgb(184, 49, 47)]'erroring on this line. "Runtime error 1004"[/COLOR]
Next i

1. This is part of a bigger code.
2. the variables within the "setting" of the ranges above are providing the correct results.

thanks for the help,

FS.
 
Not sure why we have to "Reset" as rng, rng2, etc are already "Set".
Because if you don't again use 'Set' to define the range, the code will try to put a value in the already 'set' range. It would be like this which would put "abc" into the range A1:A2

VBA Code:
Dim rng As Range

Set rng = Range("A1:A2")
rng = "abc"

Further, the 'already set range' rng was A1:A & lr whereas when you come to use rng again in that loop, you want rng to be one of the sub-ranges of that original rng.
 
Upvote 0

Excel Facts

How to total the visible cells?
From the first blank cell below a filtered data set, press Alt+=. Instead of SUM, you will get SUBTOTAL(9,)

Forum statistics

Threads
1,214,646
Messages
6,120,717
Members
448,985
Latest member
chocbudda

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top