验证集合中的唯一键

时间:2013-11-25 21:14:04

标签: excel-vba collections key vba excel

我正在尝试验证集合中是否已存在VBA集合的密钥。我使用UNIX帐户列表作为我的密钥,我已经验证过这是唯一的。然后我迭代一系列包含用户数据的工作表。由于数据的布局方式,我运行一个两遍系统,一个用于选择用户名,另一个用于关联记录中没有用户名的数据。当我在第一遍时添加用户名时,有时会抛出一个错误,说该密钥已经存在于集合中。

我最近克服此错误的尝试如下:注意:account是我编写的用于存储所有信息的类,而Accounts是集合。

Public Function ContainsKey (key as String)
    Dim retVal as Boolean
    Dim record as account

    retVal = False

    On Error GoTo Finish
    record = Account.item (key)

    If  not record = Empty Then
        retVal = True
    End If

Finish:

    ContainsKey = retVal
End Function

我已经逐步完成了代码到错误,并且if语句永远不会执行,但它仍然在抱怨重复键。我不知道该集合正在发生什么,为什么当我在将它们添加到集合中之前检查duplcates时,它会抛出一个重复的键错误。

非常感谢任何和所有帮助!提前感谢大家的帮助。

谢谢, 杰里米

2 个答案:

答案 0 :(得分:1)

要添加到我的评论和@ rheitzman的答案 - 您获得的错误编号取决于导致错误的确切原因,因此您需要检查:

Sub Tester()
Dim c As New Collection, x As Long
Dim v As Object

    For x = 1 To 10
        c.Add ActiveSheet.Cells(x, 1), "Cell" & x
    Next x

    On Error Resume Next

    v = c.Item("Cell4") 'missing Set keyword
    Debug.Print Err.Number, Err.Description
    '91   "Object variable or With block variable not set"
    If Err.Number <> 0 Then Err.Clear

    Set v = c.Item("Cell4") ' should work OK assuming key exists
    Debug.Print Err.Number, Err.Description
    '0
    If Err.Number <> 0 Then Err.Clear

    Set v = c.Item("Cell33") 'non-existent key
    Debug.Print Err.Number, Err.Description
    '5  "Invalid procedure call or argument"
    If Err.Number <> 0 Then Err.Clear

    c.Add ActiveSheet.Cells(x, 11), "Cell5" 'add duplicate key
    Debug.Print Err.Number, Err.Description
    '457 "This key is already associated with an element of this collection"

End Sub

答案 1 :(得分:0)

此代码假定帐户是一个简单的集合

        Public Function ContainsKey2(key As String) As Integer
        On Error Resume Next
            account.Add key, key
            ContainsKey2 = (Err = 457)
            If Err <> 0 And Err <> 457 Then MsgBox Err & " " & Err.Description
        End Function
相关问题