IntroductionGetting StartedAll PostsNotesAbout The Author
Reducing Workbook Bloat
Tuesday, October 06, 2009 - 4:47 PM

One of the main culprits behind workbook bloat occurs when Excel thinks a sheet's used range is bigger than it actually is. This code will test each sheet of the active workbook and either fix the problem automatically or simply alert you to it. It can be adapted for automation as well, but be aware that the code as it appears below ignores cell formatting when determining the number of rows in use. It also assumes your used range starts in the first row, but if that's not true it will not delete rows mistakenly as a result. This code could also be adapted for analyzing the used range's columns.

You can also test the used range row and column counts for the active sheet (or any sheet) through the VBE by typing "?activesheet.usedrange.rows.count" or "?activesheet.usedrange.columns.count". Control-G will bring up the immediate window from the VBE (and Alt-F11 brings up the VBE).


Option Explicit


Public Sub CheckUsedRangesForActiveWB()

    Dim ws As Worksheet, LastRow&, tempStr$, PromptBeforeDeletingUnusedRows As Boolean
    If (MsgBox("Prompt before deleting unused rows?", vbYesNo, "") = vbYes) Then _
        PromptBeforeDeletingUnusedRows = True
   
    For Each ws In ActiveWorkbook.Sheets
        With ws
            LastRow = GetLastRow(.Name)
            If (.UsedRange.Rows.Count > LastRow) Then
                If PromptBeforeDeletingUnusedRows Then
                    If (MsgBox("Excel thinks the used range for sheet " & _
                            .Name & " is " & .UsedRange.Rows.Count & _
                            " rows tall, but only " & LastRow & " rows are being used." & Chr(10) & _
                            "Deleting all rows after " & LastRow & " would solve the problem." & Chr(10) & _
                            "Do you want to do that now?", vbYesNo, "") = vbYes) Then
                        tempStr = LastRow + 1 & ":" & .Rows.Count
                        .Rows(tempStr).Delete
                    End If
                Else
                    tempStr = LastRow + 1 & ":" & .Rows.Count
                    .Rows(tempStr).Delete
                End If
            End If
        End With
    Next
   
End Sub


Private Function GetLastRow&(WSName$)
   
    Dim j&, tempInt&
    For j = 1 To ActiveSheet.Columns.Count
        tempInt = ActiveWorkbook.Sheets(WSName).Cells(ActiveSheet.Rows.Count, j).End(xlUp).Row
        If (tempInt > GetLastRow) Then GetLastRow = tempInt
    Next

End Function

<< Navigate to Tuesday, October 06, 2009 Add New Comment
No records found        
Add New Comment
Your name   
Subject   
Content   
*Required fields

January, 2009
February, 2009
March, 2009
April, 2009
May, 2009
June, 2009
July, 2009
August, 2009
September, 2009
October, 2009
November, 2009
December, 2009
IntroductionGetting StartedAll PostsNotesAbout The Author