查找函数以查找多个字符串

时间:2014-02-18 15:03:41

标签: excel vba excel-vba

我有一个包含几个可能字符串的列,我想知道它们在哪一行。

Dim lx As Integer
Dim FoundExec As Range
With Worksheets("Load " & LoadNr(1)).Range("G10:G26")
    Set FoundExec = .Find("Exec", LookIn:=xlValues)
    If Not FoundExec Is Nothing Then
        Dim FirstLoadAddress As String
        FirstLoadAddress = FoundExec.Address
        Do
            lx = FoundExec.Row
            Set FoundExec = .FindNext(FoundExec)

            'Code...

            Loop While FoundExec.Address <> FirstLoadAddress
    End If
End With

这对我来说应该是合适的,但我也希望找到值“OVS”,“OV”和“OS”,因为在这些输入之后会遵循相同的代码。

我很狂热

Dim lx As Integer
Dim FoundExec As Range
Dim FoundOVS As Range
Dim FoundOV As Range
Dim FoundOS As Range
Dim AllOSS As Range

With Worksheets("Load " & LoadNr(1)).Range("G10:G26")
    Set FoundExec = .Find("Exec", LookIn:=xlValues)
    Set FoundOVS = .Find("OVS", LookIn:=xlValues)
    Set FoundOV = .Find("OV", LookIn:=xlValues)
    Set FoundOS = .Find("OS", LookIn:=xlValues)

    Set AllOSS = Application.Union(FoundExec, FoundOVS, FoundOV, FoundOS)
    If Not AllOSS Is Nothing Then
        Dim FirstLoadAddress As String

        'Code...

        FirstLoadAddress = AllOSS.Address
        Do
            lx = AllOSS .Row
            Set AllOSS = .FindNext(AllOSS)
            Loop While AllOSS.Address <> FirstLoadAddress
    End If
End With

但是这种情况正在进行中。

有没有办法快速完成?为什么在正在进行的循环中转动第二个?

1 个答案:

答案 0 :(得分:1)

忘掉所有那些Finds,Find非常非常低效......

这样做:

With Worksheets("Load " & LoadNr(1)).Range("G10:G26")
 nr = .Rows.Count
 For r = 1 To nr
  If InStr("#Exec#OVS#OV#OS#", .Cells(r, 1) & "#") > 0 Then
   ' do whatever you need to do
  End If
 Next
End With

甚至application.match也比.Find

更有效率