在VBA

时间:2015-07-29 09:30:05

标签: excel vba excel-vba search

我需要找到列B中的单元格包含两个子字符串的行。

例如B1:B3

中的这些字符串
A string with Cows
Cows and stuff
A string with Chickens

我需要找到行B2,其中包含2个子字符串Cowsshit

到目前为止我尝试了什么:

  1. 查找doesent执行多个搜索条件的公式。 :(
  2. =MATCH(1;INDEX((B:B="Cows")*(B:B="shit"););) doesent do substrings
  3. 我忘记了很多其他的东西,
  4. 如果可能,我想要一个纯粹的VBA解决方案。

    关于这个的任何想法?

3 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

下面将列B中的所有值分配给一个数组,然后评估数组的每个元素,看它是否包含字符串“Cows”和“excrement”。

要评估元素中的字符串,我们使用InStr() Function

Sub findStrings()
    Dim wb As Workbook, ws As Worksheet
    Dim arrValues() As Variant
    Dim lrow As Long, i As Long

    Set wb = ThisWorkbook
    Set ws = wb.Sheets(1)
    lrow = ws.Cells(Rows.Count, 2).End(xlUp).Row

    arrValues = Range(Cells(1, 2), Cells(lrow, 2))

    For i = 1 To UBound(arrValues, 1)
        If InStr(1, arrValues(i, 1), "Cows") Then
            If InStr(1, arrValues(i, 1), "excrement") Then
                MsgBox ("Cell " & Cells(i, 2).Address & " contains both strings.")
                Exit Sub
            End If
        End If
    Next i
End Sub

这只会找到包含您指定的字符串的1个匹配项,如果您需要进一步的匹配,那么您将需要一个不同的解决方案。

答案 2 :(得分:0)

此函数返回包含所有单元格中包含的所有单元格的范围:

Public Function findCellsWithWords(firstWord As String, secondWord As String) As Excel.Range
    Dim wks As Excel.Worksheet
    Dim rng As Excel.Range
    Dim rngFirst As Excel.Range
    Dim rngSecond As Excel.Range
    '--------------------------------------------------


    Set wks = Excel.ActiveSheet
    Set rng = wks.Columns(2).EntireColumn

    Set rngFirst = findAll(rng, firstWord)
    Set rngSecond = findAll(rng, secondWord)


    Set findCellsWithWords = Excel.Intersect(rngFirst, rngSecond)


End Function


Public Function findAll(rng As Excel.Range, what As Variant) As Excel.Range
    Dim rngResult As Excel.Range
    Dim found As Excel.Range
    Dim firstFound As String
    '----------------------------------------------------------------------------

    With rng

        Set found = rng.Find(what)


        Do Until found Is Nothing

            If rngResult Is Nothing Then
                firstFound = found.Address
                Set rngResult = found
            Else
                Set rngResult = Excel.Union(rngResult, found)
            End If


            'Find next occurrence.
            Set found = .FindNext(found)
            If found.Address = firstFound Then Exit Do

        Loop

    End With


    Set findAll = rngResult


End Function