I want to delete a sheet based on a cell value.
For example, I want cell "T3" to have the value of the sheet I am looking to delete. There are 50+ sheets and all have number values of 4 digits (1234).
Sub Rectangle2_Click()
'deactivate alerts - stop 'are you sure you want to delete pop up'
Application.DisplayAlerts = False
'set worksheet you want to delete
sheettodelete = Range("T3").Value
'deletes sheet
Worksheets(sheettodelete).Delete
're-enable alerts
Application.DisplayAlerts = True
End Sub
The code above is one that I found that is supposed run the macro, however, it errors out at "Worksheets(sheettodelete).delete" with an error Run-tim Error '9': Subscript out of range. I checked and confirmed that the sheet does exist on the workbook.
It executes fine here, however, on a second attempt it will obviously fail since the object won't exist anymore. Also if there is a typo in T3 you will receive this error.
Here's a slight improvement that won't generate the error:
Sub test()
Dim sheetToDelete as String
Dim ws as Worksheet
Application.DisplayAlerts = False
sheetToDelete = Worksheets("SheetThatHoldsTheCell").Range("T3").value
On Error Resume Next 'To avoid the subscript out of range error
Set ws = Worksheets(sheetToDelete)
On Error Goto 0
If not ws is nothing then ws.delete 'Test if the sheet exists.
Set ws = Nothing
Application.DisplayAlerts = True
End Sub
Another solution that works is to cycle through your sheets and delete worksheet with matching name.
Sub RemoveSheet()
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Worksheets 'Checks each worksheet
If ws.Name = Range("T3").Value Then Worksheets(ws.Name).Delete
Next
Application.DisplayAlerts = True
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.