2010-08-27 77 views

回答

5

如果您使用的關鍵,當你添加的項目收集,看看是否提到這一關鍵給出了一個錯誤:

on error goto no_item 
col.Item "key" 
msgbox "Item exists" 

exit sub 

no_item:  
msgbox "Item does not exist" 

否則,您必須通過所有項目環,看看是否有一個你需要。

4

集合是基於索引的。因此,您將不得不遍歷集合來搜索一個項目。

Sub test() 
Dim iCtr As Integer 
Dim itemCount As Integer 

Dim myData As Collection 
Set myData = New Collection 

Dim searchFor As String 

myData.Add "MS", "11" 
myData.Add "Oracle", "22" 
myData.Add "Google", "33" 

'** Searching based on value 
searchFor = "Google" 

itemCount = myData.Count 
For iCtr = 1 To itemCount 
    If myData(iCtr) = searchFor Then 
     MsgBox myData(iCtr) 
     Exit For 
    End If 
Next 

'** Searching by key 
MsgBox myData.Item("22") 
End Sub 
3

我用一個簡單的工具函數遍歷一個集合。它不需要直接訪問索引,而是使用應該使用的VBA語言功能(比較變體和 - 各自的)。

Public Function ExistsIn(item As Variant, lots As Collection) 
    Dim e As Variant 
    ExistsIn = False 
    For Each e In lots 
     If item = e Then 
      ExistsIn = True 
      Exit For 
     End If 
    Next 
End Function 
+0

我不明白,這個答案有什麼問題。 – schmijos 2014-01-13 10:45:37

+0

可能是因爲這個問題被解釋爲*遍歷*,就像迭代一樣,你按照要求回答。然而字符串是散列本地查找,不需要循環。你的並不是無效的,而且是一種不必破解錯誤條件的方式,我不認爲應該被拒絕,並且肯定不會被否定。有使用錯誤和本地,使用索引循環,以及您的內置在迭代器中的使用。 – Celess 2014-11-05 22:12:08

2

@Josua Schmid:

我想在你的答案代碼可能是正確的,但可能不正確,以及。你的函數具有類型Variant的參數,然後與集合中的每個參數進行比較。但是實際比較的是什麼?在這種情況下,比較默認成員。如果集合包含某些沒有指定默認成員的自定義類的成員,則可能會出現問題。在這種情況下,運行時錯誤438對象不支持此屬性,否則會引發方法。那麼你可以添加默認成員,但即使如此,它會以一種你可能不會像我擔心的方式工作。

帶範圍的示例(對於Range-Class Value是默認成員,因此值將進行比較)。也許這正是你想要的,但也許不是。所以從我的角度來看,更好的做法是對添加到集合中的每個項目使用「密鑰」,然後嘗試通過其密鑰獲取該項目。

Debug.Print col.item(r1.Address) ' A1 Value

或者通過索引,如果沒有鑰匙使用:

Debug.Print col.item(1) ' A1 Value

Sub test() 
    Dim col As New VBA.Collection 

    Dim r1 As Range 
    Dim r2 As Range 
    Dim r3 As Range 

    Set r1 = Range("a1") 
    Set r2 = Range("b1") 
    Set r3 = Range("c1") 

    r1 = "A1 Value" 
    r2 = "B1 Value" 
    r3 = "C1 Value" 

    col.Add r1, r1.Address 
    col.Add r2, r2.Address 
    col.Add r3, r3.Address 

    Debug.Print ExistsIn(r1, col) 
    Debug.Print ExistsIn(r2, col) 
    Debug.Print ExistsIn(r3, col) 

    Dim r4 As Range 
    Set r4 = Range("d1") 
    r4 = "A1 Value" 

    Debug.Print ExistsIn(r4, col) 
End Sub 

Output:

True 
True 
True 
True 
相關問題