简体   繁体   中英

What is VBA's String Comparison Algorithm?

I am attempting to speed up the way my program searches for strings in an array. So, for example, I am writing a program which searches for the word "test" in a column of 1000 random words.

Currently my program is a simple:

If Cells(x,1).Value = "test" Then
...
End If

However, here is my idea,

If Left(Cells(x,1).Value,1) = "t" Then
If Left(Cells(x,1).Value,2) = "te" Then
... and so on ...
End If

But then I began to wonder if when I ask for VBA to test to see if the value = "test" , does it go through the process I outlined in that second code? Basically, my question is, is the second code redundant? I am unfamiliar with how VBA inherently looks for entire strings to match. If someone could shed light on what VBA goes through when I ask it to look for a Value = "string" it could really help. Thanks!

How to find if a given value exists in a range using 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

The Range.Find method has optional arguments which can be used to specify whole or partial matches, case sensitivity, etc.

How to find a given value exists in a range using Match function.

NB: The Application.Match function is similar to the WorksheetFunction.Match except that if the match is not found the Application class will return an Error Type (hence the need to define its return value as Variant , whereas the WorksheetFunction class will raise an error).

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

Limitations of Match function: The Match function only really works for exact matches (using the False argument) or approximate matches (using the True , msoTrue or msoCTrue arguments) which has some other assumptions built in, namely that the data is sorted). The Match function can only be used on a single-column range or a single-row range.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM