string - VBA 的字符串比较算法是什么?

标签 string vba algorithm excel

我正在尝试加快程序在数组中搜索字符串的速度。因此,例如,我正在编写一个程序,它在包含 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 参数) 或 近似 匹配(使用 TruemsoTruemsoCTrue 参数),其中内置了一些其他假设,即数据已排序)。 Match 函数只能用于单列范围或单行范围。

关于string - VBA 的字符串比较算法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41638559/

相关文章:

Python 字符串和整数连接

excel - for next 循环无法为变量分配值 - VBA

STL vector+sort+equality vs. unordered_set vs. using pure set 的性能(内存和速度方面)

c++ - 在二维矩阵中查找具有最大数量 0 的行

python - 如何在python中将列表转换为带引号的字符串

string - 来自第一个子字符串索引的 Shell 脚本子字符串

使用 equals() 进行 Java 字符串比较在 UDP 中无法按预期工作

Excel 自动调整行高不适用于带自动换行的合并单元格

vba - Excel - 如何在 Workbook_Open 事件上创建按钮

java - 几何形状的程序化分析