简体   繁体   中英

Hide rows conditionally in excel table with VBA

I need to be able to hide rows in a table if the first column is blank. I need the macro to work on tables in different sheets so I search for the table name first using listobjects, I have no problem getting the table name. I have seen how to accomplish this with a general range of cells, but not within a Table. Any help is appreciated.

I have a similar macro to unhide rows in the table and it works fine because it simiply loops through all rows in the ListObject variable 'MyTable' and does not have the IF statement.

    HideBlankTableRows()

    Application.ScreenUpdating = False

    Dim ws As Worksheet
    Dim myTable As ListObject
    Dim row As Range

    Set ws = ActiveSheet
    Set myTable = ws.ListObjects(1)

    For Each row In myTable.DataBodyRange
       If row.Columns(1, 1).Value = "" Then     ' Error is caused by this row
           row.Hidden = True
        End If
     Next

    End Sub

Each row In myTable.DataBodyRange will actually loop through each cell in the body of the table, which you probably don't want. Since you're only checking the first column in each row, it would be faster to loop through each row in the table using Each row In myTable.DataBodyRange.Rows .

Also, the Range object doesn't have a Columns property, so you'll have to you can use the Cells property and provide the row and column number of the cell you want to reference (row 1, column 1).

The updated code would be as follows:

For Each row In myTable.DataBodyRange.Rows
    If row.Cells(1, 1).Value = "" Then
       row.Hidden = True
    End If
Next

In addition to the fix provided by JayCal, you can utilise the ListObject properties to reference the column by name:

For Each rw In myTable.ListColumns("ColumnName").DataBodyRange
    If rw.Value = vbNullString Then
        rw.EntireRow.Hidden = True
    End If
Next

You could also use the ListObject AutoFilter method

myTable.Range.AutoFilter Field:=lo.ListColumns("ColumnName").Index, Criteria1:="<>"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM