I have a workbook which will consist of an inconsistent number of worksheets (so could be <10 or >100 at any given time).
The values column will always be in column G on each and every worksheet. I have written the following to achieve a total at the bottom of column G in each worksheet:-
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
Dim LR As Long
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
LR = Range("G" & Rows.Count).End(xlUp).Row
Range("G" & LR + 1).Formula = "=SUM(G4:G" & LR & ")"
Worksheets(ActiveSheet.Index + 1).Select
Next I
End Sub
It runs, however once the final worksheet has been totalled, I get the following runtime error:-
Run-time error '9': Subscript out of range
I've been looking at other threads and applying different approaches, some also work but trigger a runtime error 91.
If I place a end or exit to the for statement it fails after processing just one calculation.
I believe the issue lies in Worksheets(ActiveSheet.Index + 1).Select
and falling over when there is no activesheet to process.