Delete Whole Column If Header Contains "x"

  • How can I program a macro to delete columns based on what column header contains? For example, I want to delete entire columns (including header) if the corresponding cell in the header row contains the % symbol.

  • Re: Delete Whole Column If Header Contains "x"


    pepperell


    try:


    Code
    Sub remove_columns()
        For i = ActiveSheet.Columns.Count To 1 Step -1
            If InStr(1, Cells(1, i), "%") Then Columns(i).EntireColumn.Delete
        Next i
    End Sub


    filippo

  • Re: Delete Whole Column If Header Contains "x"


    Hi,


    THis will cycle through the first 10 columns if it finds % in the top cell it will delete the column.


    Does that help?


    Code
    Sub DeleteColumns()
    DIm i as integer, A as range
        For i = 10 To 1 Step -1
            Set a = Cells(1, i).Find(What:="%", LookIn:=xlValues)
            If Not a Is Nothing Then a.EntireColumn.Delete
        Next i
    End Sub


    Edit: I think filo's method above is better.

  • Re: Delete Whole Column If Header Contains "x" such as "%"


    A compromise that does all columns without checking every column.


    Code
    Sub DeleteColumns()
    Dim rng As Range
    Dim str As String
    str = "%"
        Do
            Set rng = Rows(1).Find(What:=str, LookIn:=xlValues, lookat:=xlPart)
            If rng Is Nothing Then Exit Do
            rng.EntireColumn.Delete
        Loop
    End Sub

    [h4]Cheers
    Andy
    [/h4]

    Edited once, last by Carim: Added Code Tags ().

  • Re: Delete Whole Column If Header Contains "x"



    Now were talking. : D

Participate now!

Don’t have an account yet? Register yourself now and be a part of our community!