I made a function which returns the total sum of values in a specific range from all sheets in the workbook and multiply it with a scalar. The For loop is meant to go until the last sheet in the book via the sheet Count property, but I reduced it to 2 sheets to help me figure out what was going wrong.
As it stands, the For loop exits after one iteration and I can't figure out why that is from looking at the code. The Do loop is resolving as it should.Any help is greatly appreciated!
Public Function FPP_Total()
Dim Book As Workbook: Set Book = ActiveWorkbook
Dim sheetCount As Integer: sheetCount = Book.Sheets.Count
Dim total As Long
Dim rowCount As Integer
Dim currentSheet As Worksheet
rowCount = 2
For i = 3 To 5
Set currentSheet = Book.Sheets(i)
Do
total= (total+ currentSheet.Cells(rowCount, 3).Value)
rowCount = rowCount + 1
Loop Until IsEmpty(currentSheet.Cells(rowCount, 1).Value)
Next
FPP_Total = total * 5
End Function
It looks like you are trying to sum each sheet from C2
down to the last row in the column.
Instead of creating a nested loop ( which @TheJeebo identified as the source of your problem ), you can simply identify the dynamic range in question and sum this range all at once like below. Nest this inside a sheet loop to achieve desired result
Public Function FPP_Total()
Dim ws As Worksheet 'Worksheet
Dim lr As Long 'Last Row
Dim total As Long
Dim i as Long
For i = 3 To ThisWorkbook.Sheets.Count
Set ws = ThisWorkbook.Sheets(i)
lr = ws.Range("C" & ws.Rows.Count).End(xlUp).Row
total = Application.WorksheetFunction.Sum(ws.Range("C2:C" & lr))
Next i
FPP_Total = total * 5
End Function
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.