If Not ws Is Sheet1 Then ws.Delete
The Boolean expression {object1} Is {object2}
evaluates reference equality: it will be True
if {object1}
is {object2}
.
Here ws
is a worksheet in ActiveWorkbook
, and Sheet1
is (presumably) a global identifier referring to the CodeName
of a sheet that exists in ThisWorkbook
- which may or may not be the currently active workbook.
If ThisWorkbook
isn't the ActiveWorkbook
, reference equality will fail for every single sheet, and that loop will attempt to delete them all, which is why you're getting that error.
Unless you want to delete sheets in ThisWorkbook
, you can't use reference equality to make that check.
You can go by Index
, or by name - in any case it's a good idea to ensure there's more than a single sheet in the workbook you're working with:
For Each ws In ActiveWorkbook.Worksheets
Debug.Assert ActiveWorkbook.Worksheets.Count > 1
If Not ws.Name = "Sheet1" Then ws.Delete
Next
Verify that the sheet you mean to delete has the expected index (1
) and/or the expected name; use the Project Explorer (Ctrl+R) and the Properties (F4) toolwindows for that. Bear in mind that the (Name)
property is the sheet's CodeName
identifier, which you can only use/access in the VBA project of ThisWorkbook
; you'll want to verify its Name
property - that's the user-modifiable "tab name" of the worksheet.
Sheet2
in your workbook. – dwirony