Deleting Sheet with VBA crashes Excel
excel, excel-2010, vba
Solution
The error occurs when the button that initiates the macro is located on one of the sheets that are to be deleted.
So the answer is: Do not create a button (or image linked to a macro) that deletes the sheet it is on.
If anybody can add to this answer with a reason for this error, please do so ;)
Problem
I am trying to delete a worksheet when the user click's on an image (button) in Excel. However this makes excel crash and restart, forgetting any unsaved progress. This is my sub: ``` Sub DeletePlan() Application.Calculation = xlCalculationManual Application.DisplayAlerts = False Dim SheetNamesToCopy As String SheetNamesToCopy = ActiveSheet.Name ' Check what addon sheets exists for the media, then add existing ones to string If CheckSheet("periodeplan", True) = True Then ThisWorkbook.SheetS(SheetNamesToCopy & " - periodeplan").Delete End If If CheckSheet("ukesplan", True) = True Then ThisWorkbook.SheetS(SheetNamesToCopy & " - ukesplan").Delete End If If CheckSheet("Input", True) = True Then ThisWorkbook.SheetS(SheetNamesToCopy & " - Input").Delete End If SheetS("Totalplan").Select ThisWorkbook.SheetS(SheetNamesToCopy).Delete Application.DisplayAlerts = True Application.Calculation = xlCalculationAutomatic End Sub ``` The application crashes most of the time. But not always... Any ideas what might be wrong? (I have tested and confirmed that the delete function causes the crash, but its not always the same sheet). Edit: This function is not deleting the last sheet in the workbook. There are 20 more sheets. Also i use `Application.Calculation = xlCalculationAutomatic`, because there are allot of formulas, and i do not want excel to calculate changes before all is connected sheets are deleted. Any hint or answer is appreciated :)