按字段

时间:2016-04-14 17:04:18

标签: vba ms-access access-vba ms-access-2010

我想知道是否有更快的方法来做到这一点:

我有一个对象数组。当呈现新对象时,我想确定该对象是否已存在于数组中(通过使用对象中的字段)。如果存在,只需附加其中一个字段。如果它不存在,请添加它。

这是我的代码:

If (myCollection.count <= 0) Then
        'collection must be empty, so just add it
        Set myObj= New objClass
        With myObj
            .OBJ_ID = ID
            .first_name = first_name
            .last_name = last_name
            .page_number = pageCounter 'some global variable
        End With
        myCollection.Add myObj, ID
    Else        
        Dim myObj As objClass
        'iterate through collection and see if it already exists
        For Each myObj In myCollection
            'if it does exists, just append one of the fields
            If myObj.OBJ_ID = ID Then
                myObj.page_number = myObj.page_number & "," & pageCounter
                isFound= True
            End If
        Next
        'if it doesn't exists, add it
        If (isFound = False) Then
            Set myObj= New objClass
            With myObj
                .OBJ_ID = ID
                .first_name = first_name
                .last_name = last_name
                .page_number = pageCounter
            End With
            myCollection.Add myObj
        End If
    End If

所以,我想需要优化的部分是迭代整个集合,看看是否已经存在具有给定字段值的对象。

感谢

1 个答案:

答案 0 :(得分:1)

替代

For Each myObj In myCollection
    'if it does exists, just append one of the fields
    If myObj.OBJ_ID = ID Then
        myObj.page_number = myObj.page_number & "," & pageCounter
        isFound = True
    End If
Next

On Error Resume Next
Set myObj = myCollection(ID)
On Error GoTo 0
If Not myObj Is Nothing Then
    myObj.page_number = myObj.page_number & "," & pageCounter
    isFound = True
End If

尝试设置可能的集合项然后遍历所有集合项更快