首页 文章

验证集合中的唯一键

提问于
浏览
0

我正在尝试验证集合中是否已存在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

    要添加到我的评论和@ 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

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

    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
    

相关问题