Search code examples
vbaexcelshow-hide

Hide/Show a Column based on cell value


I'm trying to hide a column and to show a column with two different excel-VBA(s) My code for hiding is working fine but when I'm unable to recall the column the VBA button just blink and do nothing. The possible reason is when I try to show the column it is not available due to hidden. What changes should I do so that it read hidden column too?

Sub SHOW()
Dim rngX1 As Range

    Set rngX1 = Worksheets("Sheet1").Range("A4:P4").Find(Range("G1"), LookIn:=xlValues, lookAt:=xlWhole)
    If Not rngX1 Is Nothing Then
        If MsgBox("Do you want to delete Column     " & Range("G1"), vbYesNo) = vbNo Then
            Exit Sub
        End If
    rngX1.EntireColumn.Hidden = False
    End If
End Sub

Solution

  • You cannot use Find() to locate content in a hidden column. You could use Match instead.

    Untested:

    Sub SHOW()
        Dim m, sht
        Set sht = Worksheets("Sheet1")
        m = Application.Match(Range("G1"), sht.Range("A4:P4"), 0)
    
        If Not IsError(m) Then
            If MsgBox("Do you want to delete Column     " & _
                                  Range("G1"), vbYesNo) = vbNo Then
                Exit Sub
            End If
            sht.Columns(m).Hidden = False
        End If
    End Sub