Hi,
Hope you can help, below I am trying to run through each sheet in an activeworkbook and perform code. Some of the code will delete an activesheet if it meets the requirements. I have assigned the upper variable as SheetsCount, this can be reduced by a sheet being deleted in the code, however my code below keeps running passed the redefined upper limit variable SheetsCount. So after a sheet is deleted and SheetsCount is redefined as -1 its orginal value the code keeps running passed the new value of SheetsCount.
I'm obviously missing something basic, and Ideas?
Sub Test()
Dim n As Long, SheetsCount As Long
SheetsCount = ActiveWorkbook.Sheets.Count
For n = 1 To SheetsCount
Sheets(n).Select
Debug.Print n
If ActiveSheet.Range("A1").Value = "1" Then
Application.DisplayAlerts = False
ActiveSheet.Delete
SheetsCount = SheetsCount - 1
n = n - 1
Sheets(n).Select
Debug.Print SheetsCount
Debug.Print n
Else: ActiveSheet.Range("A1").Value = "2"
End If
Next n
End Sub
Sorry I might not have explained this very well, but have given a basic example of my error in the code above.
Any input / ideas welcomed!
Bookmarks