根据行中的值过滤掉行而不是列

时间:2015-11-02 12:52:35

标签: excel vba excel-vba

我正在尝试编写一个宏,根据行中的值过滤掉行而不是列。 E.g:

apple   banana  pear    lime
lime    lime    lime    apple
pear    pear    pear    lime
pear    banana  lime    lime
apple   apple   apple   apple

因此,如果我为apple过滤上面的示例,我会得到第一行,第二行和最后一行。

1 个答案:

答案 0 :(得分:0)

尝试一下:

Sub Filter_By_Rows()
Dim StrToLookFor As String, _
    ToHide As Boolean, _
    LastCol As Integer, _
    Ws As Worksheet

StrToLookFor = InputBox("Hide the rows not containing that value :")
Set Ws = ThisWorkbook.ActiveSheet
LastCol = Ws.Cells(1, Ws.Columns.Count).End(xlToLeft).Column

If StrToLookFor <> vbNullString Then
    For i = 2 To Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row
        ToHide = True
        For j = 1 To LastCol
            If InStr(1, Ws.Cells(i, j), StrToLookFor) Then
                ToHide = False
                Exit For
            Else
            End If
        Next j
        Ws.Cells(i, 1).EntireRow.Hidden = ToHide
    Next i
Else
End If

或多个字符串的此版本:

Sub Multi_Filter_By_Rows()
Dim StrToLookFor As String, _
    ToHide As Boolean, _
    LastCol As Integer, _
    Ws As Worksheet, _
    A() As String

'StrToLookFor = InputBox("Hide the rows not containing these values (separated with '/') :")
StrToLookFor = "apple/banana"
Set Ws = ThisWorkbook.ActiveSheet
LastCol = Ws.Cells(1, Ws.Columns.Count).End(xlToLeft).Column

If StrToLookFor <> vbNullString Then
    If InStr(1, StrToLookFor, "/") Then
        A = Split(StrToLookFor, "/")
        For i = 2 To Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row
            ToHide = True
            For k = LBound(A) To UBound(A)
                For j = 1 To LastCol
                    If InStr(1, Ws.Cells(i, j), A(k)) Then
                        ToHide = False
                        GoTo HideNow
                    Else
                    End If
                Next j
            Next k
HideNow:
            Ws.Cells(i, 1).EntireRow.Hidden = ToHide
        Next i
    Else
        For i = 2 To Ws.Range("A" & Ws.Rows.Count).End(xlUp).Row
            ToHide = True
            For j = 1 To LastCol
                If InStr(1, Ws.Cells(i, j), StrToLookFor) Then
                    ToHide = False
                    Exit For
                Else
                End If
            Next j
            Ws.Cells(i, 1).EntireRow.Hidden = ToHide
        Next i
    End If
Else
End If
End Sub