Search code examples
excelvba

Selecting certain cells with text and hiding the columns using a macro


I tried recording a macro where any cell containing the text "Hide" is selected and then hidden. After I recorded the macro and tried to run it, I keep getting a Run-time error '1004'; No cells were found message.

I tried using this Youtube vid as a guide because this is exactly what I needed to do. Simple macro to hide columns based on cell value

Below is the resulting code from recording the macro, after following the YT vid.

Sub Hide_Columns()
'
' Hide_Columns Macro
'

'
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.SpecialCells(xlCellTypeFormulas, 2).Select
    Selection.EntireColumn.Hidden = True
    ActiveWindow.ScrollColumn = 2
    ActiveWindow.ScrollColumn = 1
End Sub


Solution

  • These macros work in my sample file.

    Sub hide()
    
    Dim i As Long
    
    For i = 2 To 100
    If Cells(1, i).Value = "Hide" Then
    Columns(i).Hidden = True
    Else
    End If
    
    Next i
    
    End Sub
    
    
    Sub unhide()
    
    Dim i As Long
    
    For i = 2 To 100
    Columns(i).Hidden = False
    Next i
    
    End Sub