如何加快重复的字符串搜索速度

时间:2016-08-27 15:03:27

标签: string vba

我有一个UDF在单元格中搜索几个子字符串。公式的输出取决于找到的子字符串:

Function StringSearch(Rge As Range) As String
Dim Str As String, Output As String
Str = Rge.Value

If InStr(Str, "words") > 0 Then Output = "Output 1"
If InStr(Str, "other words") > 0 Then Output = "Output 2"
If InStr(Str, "different words") > 0 Then Output = "Output 3"

StringSearch = Output

End Function

我在这里包含了缩减形式的函数 - 实际上,InStr函数被调用大约20次以搜索不同的字符串。

问题是功能很慢。它需要应用于数百个细胞。所以我希望能就如何加快速度提出一些建议。提前谢谢。

1 个答案:

答案 0 :(得分:0)

不确定它是否会产生太大影响,但您可以尝试使用Like运算符

Function StringSearch(s As String) As String
    If s Like "*words*" Then StringSearch = "Output 1": Exit Function
    If s Like "*other words*" Then StringSearch = "Output 2": Exit Function
    If s Like "*different words*" Then StringSearch = "Output 3": Exit Function
End Function

但Excel函数会比UDF快得多

= If( CountIf( A1, "*words*"           ), "Output 1", 
  If( CountIf( A1, "*other words*"     ), "Output 2", 
  If( CountIf( A1, "*different words*" ), "Output 3", "" )
相关问题