简体   繁体   中英

VBA: Unhide rows which contains value in an Array from a checkbox

I have three checkboxes (Cat, Dog, Mouse) and I have the below data set in excel (Letters are columns).

A      B       C
Cat   Cat     Mouse
Dog   Mouse     Cat
Mouse  Mouse     Dog
Dog    Cat       Cat

and I have the following code:

Dim num As Integer

arrcriteria = Array("Cat", "Dog", "Mouse")

Set temprange = ActiveSheet.Range("A1").End(xlDown)
Set temprange = Range(Range("A2"), temprange)

For Each z In temprange    
    z.EntireRow.Hidden = True    
    For num = 1 To 3    
       If Me.Controls("Checkbox" & num) Then    
          If InStr(1, z.Value, arrcriteria(num - 1), 1) = 1 Then    
              z.EntireRow.Hidden = False    
          Elseif InStr(1, z.offset(0,1).Value, arrcriteria(num - 1), 1) = 1 Then
              z.EntireRow.Hidden = False
          Elseif InStr(1, z.offset(0,2).Value, arrcriteria(num - 1), 1) = 1 Then
              z.EntireRow.Hidden = False
          Else    
              'Remain hidden    
          End If 
       End if
   Next num

However I want to change the code so that it hides rows when only all selected criteria are present in that row. For example if I select 'Cat' and 'Dog' the below is shown only:

 A      B       C
Dog    Mouse   Cat
Dog    Cat     Cat

Do you know how it can be done?

Thank you in advance

Will

Dim num         As Integer
Dim RowString   As String
Dim RowHide     As Boolean
Dim Z           As Range

arrcriteria = Array("Cat", "Dog", "Mouse")

Set temprange = ActiveSheet.Range("A1").End(xlDown)
Set temprange = Range(Range("A2"), temprange)

For Each Z In temprange

    With Z
        Z.EntireRow.Hidden = False
        RowString = .Value & .Offset(0, 1).Value & .Offset(0, 2).Value
        RowHide = False

        For num = 1 To 3
            If Me.Controls("Checkbox" & num) And _
            InStr(1, RowString, arrcriteria(num - 1), 1) = 0 _
            Then RowHide = True
        Next num

        If RowHide Then Z.EntireRow.Hidden = True
    End With
Next Z

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