Deleting worksheets with looping

后端 未结 2 1348
萌比男神i
萌比男神i 2021-01-22 20:22

Could you tell me someone why just every second sheet is deleted, however if I turn off the worksheets.delete line than in the message box appears all the sheet names.



        
2条回答
  •  囚心锁ツ
    2021-01-22 21:13

    What happens is that when you delete a worksheet from the Worksheets collection, the next sheet takes the index of the one you just deleted. You then increment i, skipping the next sheet that you actually wanted to delete.

    The easiest solution is to delete worksheets beginning from the end.

    For i = ThisWorkbook.Worksheets.Count To 2 Step -1
        Application.Worksheets(i).Delete
    Next i
    

提交回复
热议问题