使用多个搜索字符串来查找值是否存在?

时间:2016-06-29 07:03:24

标签: arrays excel-vba find vba excel

我试图通过我的Excel查找是否从列中找到了一个值,但无法弄清楚它是如何完成的。我的目标是找出是否存在任何过滤器选项,如果不存在则不执行任何操作,否则请继续使用我的代码。请有人就此提出建议。

ActiveSheet.Range("$A$1:$N$" & i).AutoFilter Field:=14, Criteria1:=Array( _
   "String1", "string2", "string3"), _
   Operator:=xlFilterValues


Set FoundRange = Range("$N$1:$N$" & i).Cells.Find(what:="string1", LookIn:=xlFormulas, lookat:=xlWhole)

If FoundRange Is Nothing Then
    Cells.AutoFilter
    Exit Sub

Else
End If

1 个答案:

答案 0 :(得分:0)

如果没有效果,您可以应用过滤器而不是清除过滤器。

Sub ClearAutoFilterIfNoEffect()

    Dim countVisibleRows1 As Long
    Dim countVisibleRows2 As Long
    Dim r As Range

    countVisibleRows1 = WorksheetFunction.Subtotal(103, Range("$A$1:$N$" & i))

    Range("$A$1:$N$" & i).AutoFilter Field:=14, Criteria1:=Array("String1", "string2", "string3"), Operator:=xlFilterValues

    countVisibleRows2 = WorksheetFunction.Subtotal(103, Range("$A$1:$N$" & i))

    If countVisibleRows2 = countVisibleRows1 Then
        If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
    End If

End Sub

否则你必须检查每个条件

Sub CheckAllConditionsBeforeApplyingFilter()

    With Range("$A$1:$N$" & i)
        If .Cells.Find(what:="string1", LookIn:=xlFormulas, lookat:=xlWhole) Is Nothing Then
            If .Cells.Find(what:="string2", LookIn:=xlFormulas, lookat:=xlWhole) Is Nothing Then
                If .Cells.Find(what:="string1", LookIn:=xlFormulas, lookat:=xlWhole) Is Nothing Then
                    'Clear the filter if it exists
                    If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
                    Exit Sub
                Else

                    .AutoFilter Field:=14, Criteria1:=Array("String1", "string2", "string3"), Operator:=xlFilterValues

                End If
            End If
        End If
    End With
End Sub