首页 > 解决方案 > 使用 Excel 的 2 个字符串查找和搜索

问题描述

我需要你的帮助,

是否可以根据 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

标签: excelvba

解决方案


下面的代码返回想要的结果:

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))

然后,使用 a和For Each Loopearly搜索两个字符串。Exit For.Find()


推荐阅读