使用Excel的查找和2个字符串搜索

时间:2018-10-30 19:03:42

标签: excel vba excel-vba

我需要你的帮助,

是否可以基于2个给定的值而不是1个来搜索Excel电子表格?类似于“ AND”运算符?

到目前为止,这是我所拥有的,但是我猜你是否正在寻找干草堆中的针头?

Str = "apples" AND "oranges"

With Sheets(xSheet)

    Set foundCell = .Cells.Find(What:=Str, After:=.Cells(1, 1), _
                    LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
                    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With

2 个答案:

答案 0 :(得分:3)

下面的代码返回所需的结果:

Sub TestMe()

    Dim str As String: str = "apples*oranges"
    Dim foundCell As Range

    Dim options As Variant
    options = Array(str, Split(str, "*")(1) & "*" & Split(str, "*")(0))
    Dim myVar As Variant

    For Each myVar In options
        With Worksheets(1)
            Set foundCell = .Cells.Find(What:=myVar, After:=.Cells(1, 1), _
                            LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _
                            SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
        End With            
        If Not foundCell Is Nothing Then Exit For        
    Next myVar

    If Not foundCell Is Nothing Then
        Debug.Print foundCell.Address
    End If

End Sub

我们需要搜索两个不同的字符串:"apples*oranges""oranges*apples"。拆分和反向操作非常原始:

options = Array(str, Split(str, "*")(1) & "*" & Split(str, "*")(0))

然后,将For Each Loop与早期的Exit For一起使用,.Find()搜索两个字符串。

答案 1 :(得分:1)

这是一个简单的循环选择:

Sub ApplesAndOranges()
    Dim r As Range, fruits As Range
    Set fruits = Nothing
    For Each r In ActiveSheet.UsedRange
        v = r.Value
        If v <> "" Then
            If InStr(v, "apples") <> 0 And InStr(v, "oranges") <> 0 Then
                If fruits Is Nothing Then
                    Set fruits = r
                Else
                    Set fruits = Union(fruits, r)
                End If
            End If
        End If
    Next
    MsgBox fruits.Address(0, 0)
End Sub

enter image description here

在示例中,您看到它返回所有单元格,这些单元格包含两个子字符串。