Sub HideCols()
Dim rng As Range
On Error Resume Next
Set rng = Cells(1, 6).Resize(, 22).find(what:=Cells(28, 4).Value, LookIn:=xlValues, lookat:=xlWhole)
On Error GoTo 0
If Not rng Is Nothing Then
For x = 6 To 27
If Cells(1, x).Value = Cells(28, 4).Value Then Set rng = Union(rng, Cells(1, x))
Next x
Else
MsgBox "Value: " & Cells(28, 4).Value & vbCrLf & vbCrLf & "Cannot be found!", vbExclamation, "Header Value Not Found"
End If
If Not rng Is Nothing Then
Application.ScreenUpdating = False
rng.EntireColumn.Hidden = True
Application.ScreenUpdating = True
Set rng = Nothing
End If
End Sub
Try:Code:Sub HideCols() Dim rng As Range On Error Resume Next Set rng = Cells(1, 6).Resize(, 22).find(what:=Cells(28, 4).Value, LookIn:=xlValues, lookat:=xlWhole) On Error GoTo 0 If Not rng Is Nothing Then For x = 6 To 27 If Cells(1, x).Value = Cells(28, 4).Value Then Set rng = Union(rng, Cells(1, x)) Next x Else MsgBox "Value: " & Cells(28, 4).Value & vbCrLf & vbCrLf & "Cannot be found!", vbExclamation, "Header Value Not Found" End If If Not rng Is Nothing Then Application.ScreenUpdating = False rng.EntireColumn.Hidden = True Application.ScreenUpdating = True Set rng = Nothing End If End Sub
What row are your headers on? The code assumes row 1
Sub HideCols()
Dim strMsg As String
Dim rng As Range
Const HeaderRow As Long = 1
On Error Resume Next
Set rng = Cells(HeaderRow, 6).Resize(, 22).find(what:=Cells(28, 4).Value, LookIn:=xlValues, lookat:=xlWhole)
On Error GoTo 0
If Not rng Is Nothing Then
For x = 6 To 27
If Cells(HeaderRow, x).Value <> Cells(28, 4).Value Then Set rng = Union(rng, Cells(HeaderRow, x))
Next x
Application.ScreenUpdating = False
rng.EntireColumn.Hidden = True
Application.ScreenUpdating = True
Set rng = Nothing
Else
strMsg = "Value :@D28@1@1Cannot be found!"
strMsg = Replace(strMsg, "@D28", Cells(28, 4).Value)
strMsg = Replace(strMsg, "@1", vbCrLf)
MsgBox strMsg, vbExclamation, "Header Value Not Found"
End If
End Sub
Const HeaderRow As Long = 1
Sub HideCols()
Dim strMsg As String
Dim rng As Range
Const HeaderRow As Long = 1
On Error Resume Next
Set rng = Cells(HeaderRow, 6).Resize(, 22).find(what:=Cells(28, 4).Value, LookIn:=xlValues, lookat:=xlWhole)
On Error GoTo 0
If Not rng Is Nothing Then
For x = 6 To 27
If Cells(HeaderRow, x).Value <> Cells(28, 4).Value Then Set rng = Union(rng, Cells(HeaderRow, x))
Next x
Application.ScreenUpdating = False
rng.EntireColumn.Hidden = True
Application.ScreenUpdating = True
Set rng = Nothing
Else
strMsg = "Value :@D28@1@1Cannot be found!"
strMsg = Replace(strMsg, "@D28", Cells(28, 4).Value)
strMsg = Replace(strMsg, "@1", vbCrLf)
MsgBox strMsg, vbExclamation, "Header Value Not Found"
End If
End Sub