I need to write some VBA that loops through all existing sheets (not including the first two) and deletes any sheet that matches a certain condition.
In each sheet where Cell B2 OR B3 OR B4 OR B5 OR B6 is empty. That sheet can be deleted.
I've given it a go, but there are a few issues with it:
In each sheet where Cell B2 OR B3 OR B4 OR B5 OR B6 is empty. That sheet can be deleted.
I've given it a go, but there are a few issues with it:
- It doesn't delete all the sheets. I think this is because, when I delete Sheet #4. Sheet #5 becomes sheet #4, but the macro is then running on Sheet #5? Not 100% sure, but you have to run it multiple times for it to delete all sheets that meet the criteria
- When it runs on the last sheet you get a VBA error
- I would like it to run when the user tries to close the workbook, but not 100% sure where to put the code
Code:
Sub SaveAndClose()
Dim i As Integer
For i = 3 To Worksheets.Count
Worksheets(i).Activate
If ActiveWorkbook.Worksheets(i).Range("B2").Value = "" Or ActiveWorkbook.Worksheets(i).Range("B3").Value = "" Or ActiveWorkbook.Worksheets(i).Range("B4").Value = "" Or ActiveWorkbook.Worksheets(i).Range("B5").Value = "" Or ActiveWorkbook.Worksheets(i).Range("B6").Value = "" Then
End If
Next i
ActiveWorkbook.Save
End Sub
Last edited: