减少资源来计算搜索功能

时间:2015-10-26 17:04:05

标签: vba function excel-vba excel

我目前正在编写一个执行以下功能的函数:在字符串中搜索一系列关键字的匹配项。但是我的代码效率太低,运行时间太长。有没有办法简化它并减少资源消耗?

Function SearchV(text As String, wordlist As Range)
Dim res As Variant
Dim match As Long

On Error Resume Next

For Each res In wordlist
match = InStr(UCase(text), UCase(res))

If match > 0 Then
SearchV = UCase(res)
Exit Function
End If

Next res

If match = 0 Then
SearchV = ""
End If
End Function

4 个答案:

答案 0 :(得分:0)

<强>更新

我提供了另一种方法,可以根据单词之间的空格将text拆分为数组。我知道你说可能会有一些句号或额外的空格(在下面的评论中),但我已经考虑了这些因素,你可以轻松添加它以删除更多不稳定的字符。

以文本方式搜索每个单词

Function SearchV(text As String, wordlist As Range)

Dim arr() As String, x As Long, rYes As Range

arr() = Split(text, " ") 'split text into array of words based on space

For i = LBound(arr) To UBound(arr)

    Dim sTest As String
    sTest = Replace(arr(i), ".", "") 'remove any periods
    sTest = Replace(sTest, " ", "") 'remove additional space

    Set rYes = wordlist.Find(sTest)

    If Not rYes Is Nothing Then

        SearchV = rYes
        Exit Function

    End If

Next

SearchV = ""

End Function

搜索数组方法

根据您对我(和其他人的答案)的评论,我修改了它以循环遍历数组,而不是范围。这可能会,也可能不会对速度有所帮助,但我想要展示它,因为无论如何我都有答案,可能值得测试。我还提前将一些变量设置为UCase Strings,这可能是有用的。

Function SearchV(text As String, wordlist As Range)

Dim arr() As Variant
Dim sTest As String, sAgainst As String

sAgainst = UCase$(text) 'set

arr() = wordlist

For x = LBound(arr) To UBound(arr)

    sTest = UCase$(arr(x, 1))

    If InStr(1, sAgainst, sTest) Then

        SearchV = sTest
        Exit Function

    End If

Next

SearchV = ""

End Function

答案 1 :(得分:0)

您可以使用方法查找here

示例:

Sub SearchV(text As String, wordlist As Range)

With ActiveSheet.Range(wordlist) 
    Set c = .Find(text)
End With

MsgBox c.value

End sub

答案 2 :(得分:0)

好的,所以我更新了我的答案以更好地匹配原始问题(文本中有多个单词,单词列表是单数单词)。

这会将文本拆分成一个数组,只会遍历这些单词并使用find在单词列表中找到该单词。

回到这一点是,如果有多个匹配,代码将只列出它找到的最后一个单词。

Function SearchV2(text As String, wordlist As Range)
Dim match As Variant
Dim mywords() As String
Dim i As Long

mywords = Split(text, " ")


For i = LBound(mywords) To UBound(mywords)
Set match = wordlist.Find(mywords(i), , , xlPart, , False)

If Not match Is Nothing Then
    SearchV2 = UCase(match)
ElseIf i = UBound(mywords) Then
    SearchV2 = ""
End If

Next i


End Function

答案 3 :(得分:0)

试试这个:

compile 'org.hamcrest:hamcrest-all:1.3'