VBA Show/Hide Columns or Rows in Excel
Worksheets in excel can get quite full pretty quickly and it can be useful to hide certain sections and allow them to be shown at a button click rather than requiring the user to do it all manually. Fortunately it's incredibly easy to implement this functionality, remember that you'll have to call these with parameters but add yourself a new module and enter the following subs:
Public Sub ShowHideRows(SheetName As String, RowRange As String) Dim Sheet As Worksheet Dim ChangeTo As Boolean Set Sheet = Application.Workbooks(ThisWorkbook.Name).Worksheets(SheetName) ChangeTo = Not Sheet.Rows(RowRange).EntireRow.Hidden Sheet.Rows(RowRange).EntireRow.Hidden = ChangeTo End Sub Public Sub ShowHideCols(SheetName As String, ColRange As String) Dim Sheet As Worksheet Dim ChangeTo As Boolean Set Sheet = Application.Workbooks(ThisWorkbook.Name).Worksheets(SheetName) ChangeTo = Not Sheet.Columns(ColRange).EntireColumn.Hidden Sheet.Columns(ColRange).EntireColumn.Hidden = ChangeTo End Sub
and call them from your worksheet buttons like this:
'ShowHideRows "Sheet1", "8:32"' 'ShowHideCols "Sheet2", "B:D"'
Multiple Ranges
The above code is great for individual buttons controlling individual ranges but what if you wanted one button to control multiple ranges of rows or columns? a quick loop thrown in and you're covered:
Public Sub ShowHideRows(SheetName As String, RowRange As String) Dim Sheet As Worksheet Dim ChangeTo As Boolean Dim Ranges() As String Set Sheet = Application.Workbooks(ThisWorkbook.Name).Worksheets(SheetName) Ranges = Split(RowRange, ",") Dim i As Integer For i = 0 To UBound(Ranges) ChangeTo = Not Sheet.Rows(RowRange).EntireRow.Hidden Sheet.Rows(RowRange).EntireRow.Hidden = ChangeTo Next i End Sub Public Sub ShowHideCols(SheetName As String, ColRange As String) Dim Sheet As Worksheet Dim ChangeTo As Boolean Dim Ranges() As String Set Sheet = Application.Workbooks(ThisWorkbook.Name).Worksheets(SheetName) Ranges = Split(ColRange, ",") Dim i As Integer For i = 0 To UBound(Ranges) ChangeTo = Not Sheet.Columns(Ranges(i)).EntireColumn.Hidden Sheet.Columns(Ranges(i)).EntireColumn.Hidden = ChangeTo Next i End Sub
As expected the above subs can be called as below:
'ShowHideCols "Sheet1", "I:J,N:Q,S:S"' 'ShowHideRows "Sheet1", "8:12,25:32,38:57"'
Enjoy