首页 > 解决方案 > 循环通过集合时尝试设置自定义对象时出错

问题描述

我在创建一些自定义类的集合时遇到了一些问题。它是这样的:我的“客户”类模块包含必要的公共字段。然后我有一个自定义的“客户”集合,其中包含来自我的工作表的信息,3000 件东西。其中一些是重复的,因为它们可能存在于多个工作表上,但我还是想要单独的条目,因为不同的工作表包含不同的信息。例如,例如;工作表 A 中的客户 A 包含姓名、电话和地址,工作表 B 中的相同客户 A 包含第二个电话号码、订单数量和一些其他信息,因此我希望这两个条目都不会错过任何数据。所以我的逻辑是通过循环遍历这个集合,我搜索具有相同名字和姓氏的客户,当有匹配时我' m 使用自定义函数将这两个列表“合并”在一起,只保留每个列表中的非空字段。但是,一旦我尝试将当前项目设置为新的“合并”项目,就会出现“对象不支持此属性或方法”错误。为什么会这样?我的代码如下。

For j = 1 To clientCollection.Count
    For i = j + 1 To clientCollection.Count
        If clientCollection(j).lastName = clientCollection(i).lastName Then
            If clientCollection(j).firstName = clientCollection(i).firstName Then

                'The following line generates the error
                Set clientCollection(j) = Tools.MergeClients(clientCollection(j), clientCollection(i))
                clientCollection.Remove (i)
                duplicateCounter = duplicateCounter + 1
                Exit For
            End If
        End If
    Next
Next

下面是我的 MergeClients 函数代码:

Public Function MergeClients(clientA As Client, clientB As Client) As Client
    Dim testClient As Client
    Set testClient = New Client

    With testClient
        .email = IIf(Len(clientA.email) > 0, clientA.email, clientB.email)
        .fatherName = IIf(Len(clientA.fatherName) > 0, clientA.fatherName, clientB.fatherName)
        .firstName = IIf(Len(clientA.firstName) > 0, clientA.firstName, clientB.firstName)
        .information = IIf(Len(clientA.information) > 0, clientA.information, clientB.information)
        .lastName = IIf(Len(clientA.lastName) > 0, clientA.lastName, clientB.lastName)
        .phoneA = IIf(Len(clientA.phoneA) > 0, clientA.phoneA, clientB.phoneA)
        .phoneB = IIf(Len(clientA.phoneB) > 0, clientA.phoneB, clientB.phoneB)
    End With

    Set MergeClients = New Client
    Set MergeClients = testClient

End Function

据我了解,这似乎是与我的“客户端”作为集合对象相关的错误,因为我没有问题将临时新客户端设置为 mergeclient 函数,例如

dim tempClient as Client
set tempClient = new Client

set tempClient = Tools.MergeClients(clientA, clientB)

'But if I try the same thing but with the current collection object then it fails
set clientCollection(i) = Tools.MergeClients(clientA, clientB)

我尝试尽可能地描述我的问题,希望它很清楚。我很感激对此事的一些见解!谢谢。

标签: excelvba

解决方案


我想我现在得到了你想要做的。您想要更改存储在集合中的对象。

你必须这样做

Set tmpClient = Tools.MergeClients(clientA, clientB)
With clientCollection.Item(i)
    .eMail = tempClient.eMail
    .firstName = tempClient.firstName
    ' ... and so on
End With

进一步阅读Are_Items_in_a_Collection_Read-Only


推荐阅读