Check Column For Data

Jaye7

Well-known Member
Joined
Jul 7, 2010
Messages
1,069
Hi All,

I have the following script which deletes columns if the column count is empty.

Can someone please modify the script so that if the column has data but cell 1 of the column is empty then it will put the name "Location" in cell 1 of the column.

If the column count is 0 then it would still delete the column.

Code:
Sub New_Test()
Dim iCol As Integer
With ActiveSheet.UsedRange
For iCol = .Column + .Columns.Count - 1 To 1 Step -1
If IsEmpty(Cells(65536, iCol)) And IsEmpty(Cells(1, iCol)) Then
If Cells(65536, iCol).End(xlUp).Row = 1 Then Columns(iCol).Delete
End If
Next iCol
End With
End Sub
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
This works for me

Code:
Sub New_Test()
Dim iCol As Integer
With ActiveSheet.UsedRange
For iCol = .Column + .Columns.Count - 1 To 1 Step -1
If IsEmpty(Cells(65536, iCol)) And IsEmpty(Cells(1, iCol)) Then
If Cells(65536, iCol).End(xlUp).Row = 1 Then Columns(iCol).Delete
If Cells(1, iCol) = "" Then Cells(1, iCol) = "Location"
End If
Next iCol
End With
End Sub
 
Upvote 0
My (different) approach which cuts down on loops and interaction with the sheet:

Code:
Sub New_Test()
    Dim rng As Range
    On Error Resume Next
    For Each rng In ActiveSheet.UsedRange.Rows(1).SpecialCells(xlCellTypeBlanks)
        rng.Value = IIf(Cells(Rows.Count, rng.Column).End(xlUp).Row = 1, True, "Location")
    Next
    ActiveSheet.UsedRange.Rows(1).SpecialCells(xlCellTypeConstants, xlLogical).EntireColumn.Delete
    On Error GoTo 0
End Sub
 
Upvote 0

Forum statistics

Threads
1,223,911
Messages
6,175,331
Members
452,636
Latest member
laura12345

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