Excel

Delete blank rows or columns

Ease of Use

Easy

Version tested with

2000, 2003 

Submitted by:

mdmackillop

Description:

Deletes blank rows and/or columns from the selected area or the whole of the used range of the worksheet 

Discussion:

When data is removed, it's sometimes neccessary to remove the blank rows (or columns) prior to printing or just to tidy up the worksheet. The code checks each row (column) for non-blank cells. If none are found the row (column) is deleted. 

Code:

instructions for use

			

Option Explicit Sub DeleteBlankRows() Dim Rw As Long, RwCnt As Long, Rng As Range Application.ScreenUpdating = False Application.Calculation = xlCalculationManual On Error GoTo Exits: If Selection.Rows.Count > 1 Then Set Rng = Selection Else Set Rng = Range(Rows(1), Rows(ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row())) End If RwCnt = 0 For Rw = Rng.Rows.Count To 1 Step -1 If Application.WorksheetFunction.CountA(Rng.Rows(Rw).EntireRow) = 0 Then Rng.Rows(Rw).EntireRow.Delete RwCnt = RwCnt + 1 End If Next Rw Exits: Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub Sub DeleteBlankColumns() Dim Col As Long, ColCnt As Long, Rng As Range Application.ScreenUpdating = False Application.Calculation = xlCalculationManual On Error GoTo Exits: If Selection.Columns.Count > 1 Then Set Rng = Selection Else Set Rng = Range(Columns(1), Columns(ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column())) End If ColCnt = 0 For Col = Rng.Columns.Count To 1 Step -1 If Application.WorksheetFunction.CountA(Rng.Columns(Col).EntireColumn) = 0 Then Rng.Columns(Col).EntireColumn.Delete ColCnt = ColCnt + 1 End If Next Col Exits: Application.ScreenUpdating = True Application.Calculation = xlCalculationAutomatic End Sub

How to use:

  1. Copy above code.
  2. In Excel press Alt + F11 to enter the VBE.
  3. Press Ctrl + R to show the Project Explorer.
  4. Right-click desired file on left (in bold).
  5. Choose Insert -> Module.
  6. Paste code into the right pane.
  7. Press Alt + Q to close the VBE.
  8. Save workbook before any other changes.
 

Test the code:

  1. Enter some data in random locations on your spreadsheet
  2. Press Alt + F8 to open the macro dialog box.
  3. Select DeleteBlankRows
  4. Click Run
 

Sample File:

DeleteBlanks.zip 6.6KB 

Approved by mdmackillop


This entry has been viewed 404 times.

Please read our Legal Information and Privacy Policy
Copyright @2004 - 2020 VBA Express