哪个更快更有效 - 对于循环,MATCH,FIND等?

时间:2014-03-07 19:12:16

标签: excel-vba vba excel

我正在做的是在整个范围内逐个搜索一些字符串 - 比如搜索“blah1”,如果找到则退出,否则以相同的方式在整个范围内搜索“blah2”。在一栏中搜索“blah's”。

现在我正在运行一个For循环代码,如下所示,到目前为止在我的测试中工作正常......但是想知道MATCH,FIND或其他方法是否可能更快......任何意见?

Sub test()

Dim LR As Long
LR = Sheet1.Cells(Rows.Count, "A").End(xlUp).Row

If Cells(1, "B") = "" Then
For i = 1 To LR
If Cells(i, "A") = "blah1" Then
Cells(1, "B") = Cells(i, "A").Row
Cells(1, "C") = Cells(i, "A")
Exit For
End If
Next i
End If

If Cells(1, "B") = "" Then
For i = 1 To LR
If Cells(i, "A") = "blah2" Then
Cells(1, "B") = Cells(i, "A").Row
Cells(1, "C") = Cells(i, "A")
Exit For
End If
Next i
End If

End Sub

3 个答案:

答案 0 :(得分:1)

试试这个。由于您的代码重复(对于“blah1”和“blah2”),我使用了附加功能:

Sub test()
    If Sheet1.Cells(1, "B") = "" Then
        If findString("blah1") Then Exit Sub
        If findString("blah2") Then Exit Sub
    End If
End Sub

'Function findString returns TRUE if something found and FALSE otherwise
Function findString(searchString As String) As Boolean
    Dim rng As Range, res

    With Sheet1
        Set rng = .Range("A1:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)

        res = Application.Match(searchString, rng, 0)
        'Application.Match returns error if nothing found
        findString = Not IsError(res)
        If findString Then
            .Cells(1, "B").Value = rng.Cells(res, 1).Row
            .Cells(1, "C").Value = searchString
        End If
    End With
End Function

答案 1 :(得分:0)

我是Excel Vba的新手,但我的有限理解是从细胞读取相对较慢。如果我这样做,我会将所有值读入数组,并执行与您使用的相同的for循环,但是在数组上,而不是单元格值。

要确认,您可以使用VBAs定时器功能来检查速度。

如果您想了解如何执行此操作的详细说明,请与我们联系。

答案 2 :(得分:0)

以下是如何将范围转换为数组(反之亦然)。在启用“本地”窗口的情况下逐步执行此代码,并观察会发生什么。您对 astrArray 变量特别感兴趣。

Sub ChangeArray()
'
    Dim astrArray As Variant
'
'   Dim astrArray
'       that is, with no type specified
'       is exactly equivalent
'
    Dim lngIndex As Long
    Dim strMessage As String
'
    Range("A1").Value = "This"
    Range("A2").Value = "is"
    Range("A3").Value = "only"
    Range("A4").Value = "a"
    Range("A5").Value = "test"
    astrArray = Range("A1:A5")
    For lngIndex = 1 To 5
        strMessage = strMessage & astrArray(lngIndex, 1) & " "
        Select Case lngIndex
            Case 1
                astrArray(lngIndex, 1) = "No,"
            Case 2
                astrArray(lngIndex, 1) = "it's"
            Case 3
                astrArray(lngIndex, 1) = "actually"
            Case 4
                astrArray(lngIndex, 1) = "real"
            Case 5
                astrArray(lngIndex, 1) = "life"
        End Select
    Next lngIndex
    MsgBox strMessage
    Range("A1:A5") = astrArray
End Sub

关键要求:要做到这一点,变量必须是DIMmed Variant!

要注意的另一件事是:变量是二维的,即使选择的范围是一维的。

相关问题