delete columns that have an empty or blank cell

abenitez77

Board Regular
Joined
Dec 30, 2004
Messages
149
What is a faster way of deleting columns that are empty? I am looping thru the first 200 columns to see if each column has data in a specific row. If it is blank, then I want to delete that column. My way takes about 20-30 seconds to run.

lastCol = 0
For i = 1 To 200
If ActiveCell.Value = "" Then
ActiveCell.EntireColumn.Delete
Else
ActiveCell.Offset(0, 1).Select
lastCol = lastCol + 1
End If
Next i
 

Excel Facts

Repeat Last Command
Pressing F4 adds dollar signs when editing a formula. When not editing, F4 repeats last command.
Try this:
Code:
Sub MyDeleteBlankColumns()

    Dim rw As Long
    Dim lc As Long
    
'   Get active row
    rw = ActiveCell.Row
    
'   Find last column in active row with data
    lc = Cells(rw, Columns.Count).End(xlToLeft).Column
    
'   Delete blank columns from row
    On Error Resume Next
    Range(Cells(rw, 1), Cells(rw, lc)).SpecialCells(xlCellTypeBlanks).Delete Shift:=xlToLeft
    On Error GoTo 0
    
End Sub
You could combine some lines of code to make the code shorter (not any faster though), but I like to show it this way so it is easier to understand.

The reasons why your code is slower include:
1. Loops are notoriously slower
2. Physically selecting the cells slows it down (and it often is unnecessary to use "Select" or "Activate" statements)
 
Last edited:
Upvote 0

Forum statistics

Threads
1,213,551
Messages
6,114,272
Members
448,558
Latest member
aivin

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