Marius Morthorst
Marius Morthorst

Reputation: 25

Hiding empty columns in a table in excel using VBA

I have an excel sheet with a table and its quite large so I also have a slicer to break it up in viewable pieces. My problem is that then selecting a specific unit in the slicer sometimes there will be columns in the table that's empty. I would very much like to make a button to hide them (and then have another button to unhide so I can select other units in the slicer and view new data and so on...)

My problem is that most VBA code online hides all the columns outside the table. Im not in any way fluent in VBA. I have unsuccessfully tried to modifying code I found only. From what I can see online, most codes define an area/range within a worksheet and then loops over that range and hides all empty columns. But then I try to redefine the range as the ListObjects("Table1")the code fails.

So far i have managed to make code that unhides all columns outside the table and I have tried to make a small piece of code that hides the

Sub ShowHidden()


Rows.Hidden = False
Columns.Hidden = False
End Sub

Sub HideEmptyColumns()

  ActiveSheet.ListObjects("Table1").Columns.Hidden = True
End Sub

The latter fails

Is it possible to make code that hides empty columns in a table in excel and if so, how does the code look

Kind regards

Upvotes: 0

Views: 1776

Answers (1)

EEM
EEM

Reputation: 6659

Need to use the properties of the ListObject object (Excel), in this case use the DataBodyRange to set the range to loop after. You'll also need to use Range.SpecialCells method (Excel)

Dim lo As ListObject
    Set lo = ThisWorkbook.Worksheets("DATA").ListObjects("lo.Data")     'change as required

    For Each rCol In lo.DataBodyRange.Columns
       '… Here goes the validation of the cells within the column (i.e. rCol)
       If … Then rCol.EntireColumn.Hidden = True
    Next

To unhide the columns use:

Dim lo As ListObject
    Set lo = ThisWorkbook.Worksheets("DATA").ListObjects("lo.Data")     'change as required
    lo.DataBodyRange.EntireColumn.Hidden = False

Upvotes: 1

Related Questions