2010-08-27 75 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 
相关问题