Home » excel » Excel Automation: Identifying and deleting blank work sheets

Excel Automation: Identifying and deleting blank work sheets

Posted by: admin April 23, 2020 Leave a comment


I want to delete a worksheet if it contains no data/charts/images/drawing/hyperlink object or any other embedded objects.

I find out the solution of detecting and deleting blank sheets if there is no data in the cells by using the following code:-

if ( $Worksheet_Function->CountA( $sheet->{Cells} ) == 0 ) {

but it also deletes the sheet if there are charts or non-text objects.

Is there any way to identify and delete sheets if its completely empty?

How to&Answers:

will delete the sheet if there is only formatting, but this should do what you ask

Sub chksheet()
 Dim wks As Worksheet
 Application.DisplayAlerts = False

 For Each wks In ActiveWorkbook.Worksheets

 If WorksheetFunction.CountA(Cells) = 0 And wks.DrawingObjects.Count = 0 Then
   MsgBox ("has stuff") 'or do nothing here and skip this sheet
  End If
 Next wks

 Set wks = Nothing
  Application.DisplayAlerts = True
 End Sub


You can be more thorough and go through all the related objects you want to test

Option Explicit

Sub test()
Dim WS As Worksheet

For Each WS In ThisWorkbook.Worksheets
    With WS
        'default usedrange = 1 so check cell A1 is also empty
        If .UsedRange.Count = 1 And IsEmpty(.Cells(1, 1).Value) _
            And .UsedRange.Column = 1 _
            And .UsedRange.Row = 1 _
            And .Comments.Count = 0 _
            And .Shapes.Count = 0 _
            And .Hyperlinks.Count = 0 _
            And .ListObjects.Count = 0 _
            And .OLEObjects.Count = 0 _
            And .Names.Count = 0 _
            And .QueryTables.Count = 0 _
            And .SmartTags.Count = 0 Then

            MsgBox ("BLANK")
            MsgBox ("NOT BLANK")
        End If

        End With
Next WS
End Sub