Hiding empty columns in a table in excel using VBA

浪子不回头ぞ 提交于 2021-02-17 05:59:06

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/57834329/hiding-empty-columns-in-a-table-in-excel-using-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!