Delete empty rows/columns and reset last cell

Nanogirl21

Active Member
Joined
Nov 19, 2013
Messages
330
Office Version
  1. 365
Platform
  1. Windows
Using VBA how do I delete all empty rows and columns and reset last cell?


Column A can be used to determine the last row, but the last column will always be different.
 

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"
How is your data structured?
Where are these blank rows and columns? In the middle of the data, or at the end of the data?
If at the end, there typically shouldn't be a need to delete them.

You can get the last row in column A with data like this:
Code:
Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row
 
Upvote 0
Code:
Sub t()
With ActiveSheet
    .UsedRange.AutoFilter 1, "="
    .UsedRange.SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .AutoFilterMode = False
    For Each col In .UsedRange.Offset(1).Columns
       If Application.CountA(col) = 0 Then col.EntireColumn.Delete
    Next
    lastRw = .Cells.Find("*", , xlValues, xlPart, xlByRows, xlPrevious).Row
End With
End Sub
 
Upvote 0
Code:
Sub t()
With ActiveSheet
    .UsedRange.AutoFilter 1, "="
    .UsedRange.SpecialCells(xlCellTypeVisible).EntireRow.Delete
    .AutoFilterMode = False
    For Each col In .UsedRange.Offset(1).Columns
       If Application.CountA(col) = 0 Then col.EntireColumn.Delete
    Next
    lastRw = .Cells.Find("*", , xlValues, xlPart, xlByRows, xlPrevious).Row
End With
End Sub

I tried this, but it is not working. It is refreshing all the cells, but not deleteing rows and columns that are empty.
 
Upvote 0
This will probably work better.

Code:
Sub t2()
With ActiveSheet
    For i = .UsedRange.Rows.Count To 2 Step -1
        If Application.CountA(Rows(i)) = 0 Then Rows(i).Delete
    Next
    .AutoFilterMode = False
    For j = .UsedRange.Columns.Count To 1 Step -1
       If Application.CountA(Columns(j)) = 0 Then Columns(j).Delete
    Next
    lastRw = .Cells.Find("*", , xlValues, xlPart, xlByRows, xlPrevious).Row
End With
MsgBox lastRw
End Sub

If your cells have formulas that yeild "" values in cells, then the code fails.
 
Upvote 0
How is your data structured?
Where are these blank rows and columns? In the middle of the data, or at the end of the data?
If at the end, there typically shouldn't be a need to delete them.

You can get the last row in column A with data like this:
Code:
Dim lastrow as Long
lastrow = Cells(Rows.Count,"A").End(xlUp).Row


I have data on multiple sheets. Each sheet has a different number of rows and columns. There are black rows and columns at the end of the data and the some are in the middle of the data. I was able to find this code online. It does exactly what I want, but I am trying to modify it to work on every sheet instead of only the active sheet.

PHP:
Sub RemoveBlankRowsColumns()
'PURPOSE: Remove blank rows or columns contained in the spreadsheets UsedRange
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim rngDelete As Range
Dim RowCount As Long, ColCount As Long
Dim EmptyTest As Boolean, StopAtData As Boolean
Dim RowDeleteCount As Long, ColDeleteCount As Long
Dim x As Long
Dim UserAnswer As Variant

'Analyze the UsedRange
  Set rng = ActiveSheet.UsedRange
  rng.Select

  RowCount = rng.Rows.Count
  ColCount = rng.Columns.Count
  DeleteCount = 0

'Optimize Code
  Application.ScreenUpdating = False
  Application.Calculation = xlCalculationManual
  Application.EnableEvents = False

'Loop Through Rows & Accumulate Rows to Delete
  For x = RowCount To 1 Step -1
    'Is Row Not Empty?
      If Application.WorksheetFunction.CountA(rng.Rows(x)) <> 0 Then
        If StopAtData = True Then Exit For
      Else
        If rngDelete Is Nothing Then Set rngDelete = rng.Rows(x)
        Set rngDelete = Union(rngDelete, rng.Rows(x))
        RowDeleteCount = RowDeleteCount + 1
      End If
  Next x

'Delete Rows (if necessary)
  If Not rngDelete Is Nothing Then
    rngDelete.EntireRow.Delete Shift:=xlUp
    Set rngDelete = Nothing
  End If
  
'Loop Through Columns & Accumulate Columns to Delete
  For x = ColCount To 1 Step -1
    'Is Column Not Empty?
      If Application.WorksheetFunction.CountA(rng.Columns(x)) <> 0 Then
        If StopAtData = True Then Exit For
      Else
        If rngDelete Is Nothing Then Set rngDelete = rng.Columns(x)
        Set rngDelete = Union(rngDelete, rng.Columns(x))
        ColDeleteCount = ColDeleteCount + 1
      End If
  Next x

'Delete Columns (if necessary)
  If Not rngDelete Is Nothing Then
  rngDelete.Select
    rngDelete.EntireColumn.Delete
  End If

'Refresh the current worksheet's Used Range
  ActiveSheet.UsedRange
  
  'Trim Clean
     With ActiveSheet.UsedRange
      .Value = Evaluate("if({1},trim(clean(substitute(" & .Address & ",char(160),"" ""))))")
   End With

ExitMacro:
  Application.Calculation = xlCalculationAutomatic
  Application.EnableEvents = True
  rng.Cells(1, 1).Select
  
  
End Sub
 
Upvote 0
Here is how you can run it against all sheets (new parts added in red):
Code:
[FONT=monospace]Sub RemoveBlankRowsColumns()
'PURPOSE: Remove blank rows or columns contained in the spreadsheets UsedRange
'SOURCE: www.TheSpreadsheetGuru.com

Dim rng As Range
Dim rngDelete As Range
Dim RowCount As Long, ColCount As Long
Dim EmptyTest As Boolean, StopAtData As Boolean
Dim RowDeleteCount As Long, ColDeleteCount As Long
Dim x As Long
Dim UserAnswer As Variant
[COLOR=#ff0000]Dim ws as Worksheet

For each ws in Worksheets
    ws.Activate[/COLOR]

'Analyze the UsedRange
    Set rng = ActiveSheet.UsedRange
    rng.Select

    RowCount = rng.Rows.Count
    ColCount = rng.Columns.Count
    DeleteCount = 0

'Optimize Code
    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual
    Application.EnableEvents = False

'Loop Through Rows & Accumulate Rows to Delete
    For x = RowCount To 1 Step -1
        'Is Row Not Empty?
         If Application.WorksheetFunction.CountA(rng.Rows(x)) <> 0 Then
             If StopAtData = True Then Exit For
         Else
             If rngDelete Is Nothing Then Set rngDelete = rng.Rows(x)
             Set rngDelete = Union(rngDelete, rng.Rows(x))
             RowDeleteCount = RowDeleteCount + 1
         End If
    Next x

'Delete Rows (if necessary)
    If Not rngDelete Is Nothing Then
        rngDelete.EntireRow.Delete Shift:=xlUp
        Set rngDelete = Nothing
    End If
  
'Loop Through Columns & Accumulate Columns to Delete
    For x = ColCount To 1 Step -1
         'Is Column Not Empty?
        If Application.WorksheetFunction.CountA(rng.Columns(x)) <> 0 Then
            If StopAtData = True Then Exit For
        Else
            If rngDelete Is Nothing Then Set rngDelete = rng.Columns(x)
            Set rngDelete = Union(rngDelete, rng.Columns(x))
            ColDeleteCount = ColDeleteCount + 1
        End If
    Next x

'Delete Columns (if necessary)
    If Not rngDelete Is Nothing Then
        rngDelete.Select
        rngDelete.EntireColumn.Delete
    End If

'Refresh the current worksheet's Used Range
    ActiveSheet.UsedRange
  
  'Trim Clean
    With ActiveSheet.UsedRange
        .Value = Evaluate("if({1},trim(clean(substitute(" & .Address & ",char(160),"" ""))))")
    End With

ExitMacro:
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    rng.Cells(1, 1).Select
  
[COLOR=#ff0000]Next ws[/COLOR]
  
End Sub[/FONT]
 
Upvote 0

Forum statistics

Threads
1,214,585
Messages
6,120,394
Members
448,957
Latest member
Hat4Life

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top