The sample dataset showcases: Salesman, Product, and Net Sales.
Example 1 – Apply Excel VBA to Hide Columns Based on the Cell Value
X is displayed in a cell. To hide the entire column:
STEPS:
- Go to the Developer tab.
- Select Visual Basic.
- In the VBA window, select Insert.
- Choose Module.
- Enter the following code.
Sub HideCol_CellValue()
Dim c As Range
For Each c In ActiveWorkbook.ActiveSheet.Rows("10").Cells
If c.Value = "X" Then
c.EntireColumn.Hidden = True
End If
Next c
End Sub
- Save the file and press F5 to run the code.
- Close the VBA window.
This is the output.
Example 2 – Hide Columns Based on Criteria in Real-time with Excel VBA
STEPS:
- Double-click the sheet name.
- Click View Code.
- In the VBA window, enter the following code.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Range("G4").Value = "Product" Then
Columns("D").EntireColumn.Hidden = True
ElseIf Range("G4").Value = "Net Sales" Then
Columns("C").EntireColumn.Hidden = True
End If
End Sub
- In G4, enter Product.
- The Net Sales column is hidden.
Example 3 – Embed VBA to Hide a Single Column in Excel
STEPS:
- Go to the Developer tab.
- Select Visual Basic.
- In the VBA window, select Insert.
- Choose Module.
- Enter the following code.
Sub Hide_Column()
Columns("C").Hidden = True
End Sub
- Press F5 to run the code.
It will hide column C.
Read More: Excel VBA to Hide Columns Using Column Number
Example 4 – Hide Multiple Columns in Excel with VBA
- Go to the Developer tab.
- Select Visual Basic.
- In the VBA window, select Insert.
- Choose Module.
- Enter the following code.
Sub Hide_MultipleColumns()
Columns("C:D").EntireColumn.Hidden = True
End Sub
- Press F5 to run the code.
Columns C and D are hidden.
Example 5 – Use VBA to Hide Alternate Columns
Hide columns C and E.
STEPS:
- Go to the Developer tab.
- Select Visual Basic.
- In the VBA window, select Insert.
- Choose Module.
- Enter the following code.
Sub Hide_AlternativeColumns()
Dim p As Integer
For p = 2 To 4
Cells(1, p + 1).EntireColumn.Hidden = True
p = p + 1
Next p
End Sub
- Save the file.
- Press F5 to run the code.
It will hide columns C and E.
Example 6 – Hide Empty Columns with VBA in Excel
Column C is empty.
STEPS:
- Go to the Developer tab.
- Select Visual Basic.
- In the VBA window, select Insert.
- Choose Module.
- Enter the following code.
Sub Hide_EmptyColumns()
Dim p As Integer
For p = 2 To 4
If Cells(4, p).Value = "" Then
Columns(p).Hidden = True
End If
Next p
End Sub
- Save the file.
- Press F5 to run the code.
This is the output.
Download Practice Workbook
Download the following workbook.