2013-01-07 31 views
1
If UBound(Filter(myArray, Sheets(i).Cells(1, j).Value, True)) = -1 Then 
'take action 
End if 

我用這個語法來在細胞中發現的元素(1,j)的(例如,「烯丙基」)比較的數組中的所有元素(例如,「馬利」 ,「凱特」,「貝克斯」),並在未找到完全匹配時採取行動。 麻煩的是,基於這行代碼,它似乎「盟友」被認爲是匹配「不正當」(可能是因爲「盟友」是來自「不正當」的子字符串),而我想要「盟友」被識別爲不同於「馬利」。VBA陣列 - 檢查嚴格(未近似的)匹配

的語法達到這個任何幫助嗎?謝謝!

回答

2

過濾器將返回任何部分匹配的項目。微軟提出的解決方法是,然後搜索已過濾的數組以獲得完全匹配。

Function FilterExactMatch(astrItems() As String, _ 
          strSearch As String) As String() 

    ' This function searches a string array for elements 
    ' that exactly match the search string. 

    Dim astrFilter() As String 
    Dim astrTemp()  As String 
    Dim lngUpper   As Long 
    Dim lngLower   As Long 
    Dim lngIndex   As Long 
    Dim lngCount   As Long 

    ' Filter array for search string. 
    astrFilter = Filter(astrItems, strSearch) 

    ' Store upper and lower bounds of resulting array. 
    lngUpper = UBound(astrFilter) 
    lngLower = LBound(astrFilter) 

    ' Resize temporary array to be same size. 
    ReDim astrTemp(lngLower To lngUpper) 

    ' Loop through each element in filtered array. 
    For lngIndex = lngLower To lngUpper 
     ' Check that element matches search string exactly. 
     If astrFilter(lngIndex) = strSearch Then 
     ' Store elements that match exactly in another array. 
     astrTemp(lngCount) = strSearch 
     lngCount = lngCount + 1 
     End If 
    Next lngIndex 

    ' Resize array containing exact matches. 
    ReDim Preserve astrTemp(lngLower To lngCount - 1) 

    ' Return array containing exact matches. 
    FilterExactMatch = astrTemp 
End Function 

此代碼是從http://msdn.microsoft.com/en-us/library/office/aa164525%28v=office.10%29.aspx

2

如果您不需要使用過濾器,然後下面的代碼片段會工作

Dim v 
Dim bMatch As Boolean 
bMatch = False 

For Each v In myArray 
    'compare strings 
    If StrComp(CStr(v), Sheets(i).Cells(1, j).Value, vbTextCompare) = 0 Then 
     bMatch = True 
    End If 
Next 

If Not bMatch Then 
'do something 
End If 
+0

謝謝兩位非常感謝! – Sam

2

如果陣列只用於這種比較和沒有必要採取對於其他任何事情,你也可以通過添加你自己的分隔符來強制全字比較,這些分隔符從未出現在數據中 - 也許是方括號。
所以,如果你改變你的數組包含 「[馬利]」, 「[凱特]」, 「[小貝]」
那麼你的條件爲:

If UBound(Filter(myArray, "[" & Sheets(i).Cells(1, j).Value & "]", True)) = -1 
3
IsInArray = Not IsError(Application.Match(stringToBeFound, arr, 0))