Do loop - sum up loops together

Alpacino

Well-known Member
Joined
Mar 16, 2011
Messages
511
How do u write a code so that each time it loops through a statement it adds it up depending on the number of loops.

Eg I want to count the number of times H appears in cells in sheets 1 to 12

Application.worksheetfunction.countif(sheets(x).range("C4:AK4"),"H")

I want to loop this 12 times each time sheet x from 1 to 12 add values together at the end.

Thanks in advance
 

Excel Facts

How to create a cell-sized chart?
Tiny charts, called Sparklines, were added to Excel 2010. Look for Sparklines on the Insert tab.
You don't need a Do Loop. You need a For Next Loop:

Code:
Sub test()
Dim x As Long, y As Long
For x = 1 To 12
    y = y + Application.WorksheetFunction.CountIf(Sheets(x).Range("C4:AK4"), "H")
Next x
MsgBox y
End Sub
 
Upvote 0
Code:
For x = 1 To 12
    y = y + Application.WorksheetFunction.CountIf(Sheets(x).Range("C4:AK4"), "H")
Next x
MsgBox y
 
Upvote 0
Maybe

Code:
asum = 0
For x = 1 To 12
    asum = asum + WorksheetFunction.CountIf(Sheets(x).Range("C4:AK4"), "H")
Next x
 
Upvote 0
You shouldn't need the asum=0 line. If you dim the variable as Long, it will automatically intialize the value to 0.
 
Upvote 0

Forum statistics

Threads
1,224,603
Messages
6,179,856
Members
452,948
Latest member
UsmanAli786

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