什么是VBA的string比较algorithm?
我正试图加快我的程序search数组中的string的方式。 所以,例如,我正在编写一个程序,在1000个随机单词的列中search单词“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
testingvalue = "test"
,是否经历了我在第二个代码中概述的过程? 基本上,我的问题是,第二个代码是多余的? 我不熟悉VBA如何查找整个string来匹配。 如果有人能够说明VBA经历的是什么,当我要求它寻找Value = "string"
,这真的可以帮上忙。 谢谢!
如何使用Range.Find
方法find给定值是否存在于一个范围内:
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
函数在一个范围内find给定值。
注意: Application.Match
函数类似于WorksheetFunction.Match
只是如果找不到匹配, Application
类将返回一个错误types(因此需要将其返回值定义为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
参数),这些匹配内置了一些其他假设,即数据被sorting)。 Match
function只能用于单列或单列的范围。