简体   繁体   中英

How to hide a row if a cell in one column contains a certain string

I have a worksheet that is set out like a calendar - Every column is a working day until the end of the month, Column A is the name of a task, each row is a specific task (8 tasks), and then the next month underneath using the same tasks.

Currently we are using a toggle button for each task with the following code to hide each row (Other rows removed to save space):

Private Sub ToggleButton13_Click()
If ToggleButton13.Value = True Then

        Rows(22).EntireRow.Hidden = True

    Else

        Rows(22).EntireRow.Hidden = False

    End If
End Sub

This was fine, but this calendar now keeps growing with additional tasks requiring us to go into each togglebutton and every row to change it accommodating the new task. As the calendar doesn't belong to me, I've got no experience with any form of coding so found this previously, the actual user doesn't want to have to change this manually (I can understand why, it can be time consuming). I'm wondering if we can use the 'IF' function with the togglebutton?

So effectively:

  1. Everything is Visible
  2. Press ToggleButton13

    IF ColumnA cell contains 'Admin' then hide the row ELSE If ColumnA cell doesn't contain 'Admin' then show the row

Assumption: Entries in column A are continuous... it will come handy as your sheet keeps growing, so just need to follow a format.

     Private Sub ToggleButton13_Click()

        Dim indexCol, indexRow as Integer
        dim myKey as String

        myKey = "Admin"


        indexCol = 1 ' For Column A
    indexRow = 2 'row index from where the first entry starts in the Column


    ' loop will traves each row utill columnA entry correspondig to that row is not empty
    Do While IsEmpty(ActiveSheet.Cells(indexRow, indexCol)) = False 

    If ActiveSheet.Cells(indexRow, indexCol).Value = myKey Then

            Rows(indexRow).EntireRow.Hidden = True

        Else

            Rows(indexRow).EntireRow.Hidden = False

        End If

        indexRow = indexRow + 1

    Loop    

    End Sub

Try a general loop, similar to what Ron Rosenfield suggested in the comments. Will comment through it since you said you're inexperienced with coding:

Dim i, LR as Integer 'i will be variable for row in the loop, LR as variable for last row
LR = Cells(Rows.Count,1).End(xlUp).Row 'Determines the last row based on contiguous cells in column 1, aka column A
For i = 2 to LR 'Starting at Row 2 with the assumption that you have headers
    If Cells(i,1).Value="Admin" Then 'Cells(row,column) here is column 1, aka column A.  
        Rows(i).EntireRow.Hidden=True 'Hides row if true
    Else
        Rows(i).EntireRow.Hidden=False 'Ensure row is not hidden if false.
    End If
Next i

This would be inside your button click macro.

Two ways I can think of:

Cycle through each row and set the hidden property.
As the code is behind the ToggleButton we don't need to specify the sheet name. The code will run on the currently active sheet which is the correct sheet because you pressed the ToggleButton on it.

As ToggleButton returns either TRUE or FALSE we can just set the hidden property to that value.

Private Sub ToggleButton1_Click()
    Dim rDataRange As Range
    Dim rCell As Range

    'Set rDataRange = Range("A2", Cells(Rows.Count, 1).End(xlUp))
    'Take into account hidden rows:  
    Set rDataRange = Range("A2", HiddenLastCell(ActiveSheet))

    For Each rCell In rDataRange
        If rCell = "Admin" Then
            Rows(rCell.Row).EntireRow.Hidden = ToggleButton1
        End If
    Next rCell
End Sub 

Setting the range in rDataRange uses this function to find the last cell even if it's hidden:

Public Function HiddenLastCell(wrkSht As Worksheet) As Range

    Dim rLastCell As Range
    Dim bHasHiddenData As Boolean
    Dim rSearch As Range
    Dim lLastCol As Long, lLastRow As Long
    Dim lRow As Long

    With wrkSht
        Set rLastCell = .Columns(1).Find("*", , , , xlByColumns, xlPrevious)

        If Not rLastCell Is Nothing Then
            bHasHiddenData = rLastCell.Row <> .UsedRange.Rows.Count
        Else
            bHasHiddenData = .UsedRange.Rows.Count > 1
        End If

        If bHasHiddenData Then
            Set rSearch = .Range(.Cells(1, 1), .Cells(.UsedRange.Row + .UsedRange.Rows.Count - 1, 1))
            For lRow = rSearch.Rows.Count + 1 To 2 Step -1
                If .Cells(lRow, 1) = vbNullString And .Cells(lRow - 1, 1) <> vbNullString Then
                    Set HiddenLastCell = .Cells(lRow, 1)
                End If
            Next lRow
        Else
            On Error Resume Next
            lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
            lLastRow = .Columns(1).Find("*", , , , xlByColumns, xlPrevious).Row
            If lLastCol = 0 Then lLastCol = 1
            If lLastRow = 0 Then lLastRow = 1
            Set HiddenLastCell = wrkSht.Cells(lLastRow, lLastCol)
            On Error GoTo 0
        End If
    End With

End Function

Use AutoFilter to hide the rows.
Add this code to the button:

Private Sub ToggleButton1_Click()
    FilterAdmin ToggleButton1.Value
End Sub

This code will apply or remove the filter:

Sub FilterAdmin(ToggleOn As Boolean)

    Dim rDataRange As Range
    Dim rLastCell As Range

    With ThisWorkbook

        If ToggleOn Then
            Set rLastCell = LastCell(.Worksheets("Sheet1"))
            With .Worksheets("Sheet1")
                'Get reference to data range (A1 to last used cell).
                'Or you can manually set the range.
                Set rDataRange = .Range(.Cells(1, 1), rLastCell)

                'If auto-filter isn't turned on then turn it on.
                If Not .AutoFilterMode Then rDataRange.AutoFilter

                'Remove any applied filters.
                If .FilterMode Then .ShowAllData

                rDataRange.AutoFilter Field:=1, Criteria1:="<>Admin", Operator:=xlAnd
            End With
        Else
            If .Worksheets("Sheet1").FilterMode Then .Worksheets("Sheet1").ShowAllData
        End If
    End With

End Sub  

This function will return the last cell that contains data and is used in the above procedure:

Public Function LastCell(wrkSht As Worksheet, Optional Col As Long = 0) As Range

    Dim lLastCol As Long, lLastRow As Long

    On Error Resume Next

    With wrkSht
        If Col = 0 Then
            lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
            lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
        Else
            lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
            lLastRow = .Columns(Col).Find("*", , , , xlByColumns, xlPrevious).Row
        End If

        If lLastCol = 0 Then lLastCol = 1
        If lLastRow = 0 Then lLastRow = 1

        Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
    End With
    On Error GoTo 0

End Function  

You could change the sheet references in the code to use ActiveSheet rather than Sheet1 (again, the correct sheet will be active when you press the toggle button).

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