2017-01-13 33 views
1

我試圖加快我的程序搜索數組中的字符串的方式。因此,例如,我正在編寫一個程序,在1000個隨機詞的列中搜索單詞「test」。什麼是VBA的字符串比較算法?

目前我的程序是一個簡單的:

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"它可以真正幫助。謝謝!

+2

爲什麼你不使用'Range.Find'方法? –

+1

或'Match'功能?如果你正在尋找優化,肯定有更好的內置方法,而不是依靠(似乎是)蠻力細胞迭代。 –

+0

一旦開始讀取單元格,任何好處都可能消失 - 讀取表單以讀取值的開銷相對較大,因此重複執行該操作不是一個好方向。 –

回答

0

如何找到如果使用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函數在一個範圍內找到給定值。

NB:該Application.Match功能類似於WorksheetFunction.Match不同之處在於,如果匹配未發現Application類將返回一個錯誤類型(因此需要來定義它的返回值作爲Variant,而WorksheetFunction類將提出錯誤)。 Match功能

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功能才真正適用於完全匹配(使用False參數)或近似匹配(使用TruemsoTruemsoCTrue參數),它具有內置了一些其他假設in,即數據被排序)。 Match函數只能用於單列範圍或單行範圍。