Hi ribhead,
I was about to write a quick response and I went back and looked at your code. What are you trying to do?
1. Your outer
For says do this once for each sheet.
2. You increment
n continually without ever resetting it. As you have never initialised it, it will start out as zero. First time through it will become 1, second time 2, third time 3, etc.
3. You inner For is driven from
n. First time it will be done twice, second time once, third and further times not at all (because n is greater than 2 and climbing).
4. Deleting sheets - First time through the outer loop you will delete sheet 1. What was sheet 2 will now become sheet 1, etc. Now you delete sheet 2 (which was sheet 3) so the old sheet 4, which had become sheet 3 now becomes sheet 2, etc. Second time through your outer loop you delete sheet 2 (which was originally sheet 4). Further times through you won't delete any sheets.
5. The overall effect is that, no matter how many sheets you have is that you delete sheets 1, 3 and 4 (unless of course you had less than that to start with)
My original quick response was going to be that when you have deleted a sheet all the others move down 1. So say you have 3 sheets and you delete sheet 1, you are left with sheets 1 and 2 (which used to be sheets 2 and 3). You increment your loop counter and delete sheet 2 (which was sheet 3). There are now no more sheets so when you increment your loop counter and try and delete sheet 3 you get 'subscript out of range'. The way round this is to work from the end backwards - make your loop control:
For n = Sheets.Count to 1 Step -1, but note that you cannot delete ALL the sheets in a workbook - you must leave 1.
Hi Clive,
While I've been writing this epistle I see that you have posted twice (I must be getting slow at typing as well as thinking)
Both your code samples try and delete all sheets. The second also suffers from the same problem ribhead has and should get 'subscript out of range'.
Enjoy,
Tony