Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quickest way to clear all sheet contents VBA

Tags:

excel

vba

I have a large sheet that I need to delete all the contents of. When I try to simply clear it without VBA it goes into not responding mode. When using a macro such as:

Sub ClearContents ()  Application.Calculation = XlManual  Application.ScreenUpdating = False    Sheets("Zeroes").Cells.ClearContents   Application.ScreenUpdating = True End Sub 

It also doesn't respond. What's the quickest way to do this?

like image 752
hc91 Avatar asked Apr 30 '15 12:04

hc91


People also ask

How do I clear contents in Excel VBA?

Code: Range (“A1:C3”).Delete It will delete the mentioned cell values, just like our clear method. You can use the VBA CELLS property. In VBA concepts, cells are also the same, no different from normal excel cells. read more with a worksheet name if you want to delete all the cell's data.

Can you clear an entire worksheet in Excel?

To clear all contents, formats, and comments that are contained in the selected cells, click Clear All. To clear only the formats that are applied to the selected cells, click Clear Formats. To clear only the contents in the selected cells, leaving any formats and comments in place, click Clear Contents.


1 Answers

The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:

Sheets("Zeros").UsedRange.ClearContents 

Alternately, you can delete the sheet and re-add it:

Application.DisplayAlerts = False Sheets("Zeros").Delete Application.DisplayAlerts = True Dim sheet As Worksheet Set sheet = Sheets.Add sheet.Name = "Zeros" 

EDIT: (@tavnab and @Azura)
Heads up for future readers, you cannot delete a sheet if it's the last/only one in the workbook.
In that case, you can add the new blank sheet first, delete the old one, and finally rename that new sheet to the old sheet's name. Also note that eliminating a sheet will create conflicts with formulas in other sheets that were referencing the recently eliminated one, recreating the sheet may not solve that issue.

like image 110
Comintern Avatar answered Oct 21 '22 21:10

Comintern