Delete All Empty Columns Until Final Empty Column

BrianExcel

Well-known Member
Joined
Apr 21, 2010
Messages
975
I am using the following code to delete all empty columns in a specific range:

VBA Code:
    Do Until LastColumn = 0
        If WorksheetFunction.CountA(Columns(LastColumn)) = 0 Then
            Columns(LastColumn).Delete
        End If
            LastColumn = LastColumn - 1
        Loop

The above code works fine. I need to perform the same operation on another data set that is two columns over from the last column in the original data set. So if the last column first set of data ends at column D, I have a blank column in E (to create some separation between the two tables), and then the new data set starting in Column F.

The problem is that the code above is also deleting that empty column in between the first and second data sets.

Is there any easy change I can make to the above code to keep that separating empty column but delete the rest?
 

Excel Facts

Difference between two dates
Secret function! Use =DATEDIF(A2,B2,"Y")&" years"&=DATEDIF(A2,B2,"YM")&" months"&=DATEDIF(A2,B2,"MD")&" days"
It would be better if you post enough of the code to show how the 'LastColumn' variable is initialized.
 
Upvote 0
This might work for you.
VBA Code:
Do Until LastColumn = 0
        If WorksheetFunction.CountA(Columns(LastColumn)) = 0 And _
               WorksheetFunction.CountA(Columns(LastColumn - 1) = 0 Then
            Columns(LastColumn).Delete
        End If
            LastColumn = LastColumn - 1
        Loop
 
Upvote 0

Forum statistics

Threads
1,213,536
Messages
6,114,215
Members
448,554
Latest member
Gleisner2

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