VBA code to delete data in a sheet
Return to VBA Code Examples In this Article This tutorial will teach you how to delete or clear a worksheet using VBA. Delete WorksheetUse the delete command to delete a worksheet. Delete Worksheet by Name
Delete Worksheet by Index Number This code deletes the first worksheet in the workbook:
This code deletes the last worksheet in the workbook:
Delete Worksheet Without PromptWhen you attempt to delete a worksheet, Excel will ask you to confirm your action: You can disable these prompts (alerts) by toggling DisplayAlerts:
Delete Sheet If It ExistsIf you attempt to delete a worksheet that does not exist, VBA will generate an error. With On Error Resume Next you can tell VBA to delete a sheet if it exists, otherwise skip to the next line of code:
You could also use our RangeExists function to check if a sheet exists and if so delete it.:
Clear SheetThis code will clear an entire sheet of contents, formats, and everything else:
Clear Sheet ContentsThis code will clear an entire sheet’s contents. It will leave formatting, comments, and everything else alone:
VBA Coding Made EasyStop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! Learn More!! Clear Sheet UsedRangeThe above examples will clear ALL cells in a worksheet. This can be very time consuming in large sheets. If you use the UsedRange instead, VBA will only clear the “used” cells that contain values, formats, etc. Return to VBA Code Examples In this Article In VBA it’s fast and easy to clear an entire sheet (or worksheet). Clear ActiveSheetClear Everything (Contents, Formats, Comments, etc.)This will clear the Activesheet’s cells of all cell properties: contents, formats, comments, etc:
Clear ContentsInstead, you can clear ONLY the cell contents:
Clear Formatsor only the Cell Formats:
By typing: Cells.Clear into the VBA Editor you can see the list of Clear methods available to you: Delete Worksheet UsedRangeYou can also delete the entire worksheet’s UsedRange. This can also delete objects (shapes, charts, textboxes).
Clear Sheet (By Name)To clear a specific sheet use the following code where “Sheet1” is the name of the sheet to clear:
VBA Coding Made EasyStop searching for VBA code online. Learn more about AutoMacro - A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users! Learn More!! Clear Worksheet (From Variable)To clear a sheet defined by an object variable use the following code: |