我正在尝试加快程序在数组中搜索字符串的速度。因此,例如,我正在编写一个程序,它在包含 1000 个随机单词的列中搜索单词“test”。
目前我的程序很简单:
If Cells(x,1).Value = "test" Then
...
End If
不过,这是我的想法,
If Left(Cells(x,1).Value,1) = "t" Then
If Left(Cells(x,1).Value,2) = "te" Then
... and so on ...
End If
但后来我开始怀疑,当我要求 VBA
进行测试以查看 value = "test"
时,它是否经历了我在第二个代码?基本上,我的问题是,第二个代码是多余的吗?我不熟悉 VBA 本身如何寻找要匹配的整个字符串。如果有人能阐明当我要求 VBA 查找 Value = "string"
时 VBA 经历了什么,它真的会有所帮助。谢谢!
最佳答案
如何使用 Range.Find
method 查找给定值是否存在于范围内:
Dim rng as Range
Dim found as Range
Dim val As String
val = "test" '## Modify as needed
Set rng = Range("A1:A1000") '## Modify as needed
Set found = rng.Find(val)
'The Range.Find method will return a Nothing if the value is not found
If found Is Nothing Then
MsgBox "Not found!"
Else
'do something with it...
End If
Range.Find
方法具有可选参数,可用于指定全部或部分匹配、区分大小写等。
如何使用 Match
函数查找范围内存在的给定值。
注意:Application.Match
函数类似于 WorksheetFunction.Match
除了如果匹配未找到 Application
类将返回错误类型(因此需要将其返回值定义为Variant
,而WorksheetFunction
类将引发一个错误。
Dim rng as Range
Dim found as Variant
Dim val as String
val = "test" '## Modify as needed
Set rng = Range("A1:A1000") '## Modify as needed
found = Application.Match("test", rng, False)
'The Application.Match function will return an Error Type if the val is not found
If IsError(found) Then
MsgBox "Not found!"
Else
'do something with it
End If
Match
函数的局限性:Match
函数仅适用于精确匹配(使用 False
参数) 或 近似 匹配(使用 True
、msoTrue
或 msoCTrue
参数),其中内置了一些其他假设,即数据已排序)。 Match
函数只能用于单列范围或单行范围。
关于string - VBA 的字符串比较算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41638559/