VBA正在从引用同一集合的循环上的集合中删除用户。计数

VBA正在从引用同一集合的循环上的集合中删除用户。计数,vba,excel,Vba,Excel,我正在使用一张列出程序用户的表格。用户可能会被多次列出,所以我制作了一个程序来过滤用户的数据并通过电子邮件发送给他们。为此,我使用收集方法列出用户和电子邮件信息 我正在编写一段代码,将删除在我的工作表中没有条目的用户。基本上,如果他们的用户名不存在,请从集合中删除他们 我很确定问题出在从n=1到MyPeople.Count的For循环中,因为我正在积极地从MyPeople中删除条目。共有34个要启动,删除6个总数后,在29时出错。问题是我不知道如何解决这个问题 You can see my at

我正在使用一张列出程序用户的表格。用户可能会被多次列出,所以我制作了一个程序来过滤用户的数据并通过电子邮件发送给他们。为此,我使用收集方法列出用户和电子邮件信息

我正在编写一段代码,将删除在我的工作表中没有条目的用户。基本上,如果他们的用户名不存在,请从集合中删除他们

我很确定问题出在从n=1到MyPeople.Count的For循环中,因为我正在积极地从MyPeople中删除条目。共有34个要启动,删除6个总数后,在29时出错。问题是我不知道如何解决这个问题

You can see my attempts in the If cel.Value=0 section
代码:


您的循环应该是这样的:

n = MyPeople.Count
While n > 0
    [do code]
    n = n - 1
Loop

这是我想到的。上述评论是正确的。我需要扭转这个循环。如您所见,现在我从n=mypeople.count数到1。在这样做之后:

Sub RemoveEmptyUsers()
Dim RemoveDecider As Integer
RemoveDecide = 0
Dim test As Integer
test = 0
Set rng = Range("B17", Range("B65536").End(xlUp).Offset(1))
MsgBox (MyPeople.Count)
    For n = MyPeople.Count To 1 Step -1
        For Each cel In rng
            If cel.Value = MyPeople(n).SiView Then
                Exit For
            End If
            If cel.Value = 0 Then 'the last empty cell after all entries are checked for user
                MsgBox (MyPeople(n).FirstName & " has been removed")
                MyPeople.Remove (n)
                Exit For
            End If
        Next cel
    Next n
End Sub

当执行这样的循环时,最好从最高值开始,然后转到1。当你删除一行时,你的索引会变得混乱。总是从末尾开始删除,然后向后移动。这一点很好。如果我自己解决了这个问题,我会试试,然后回到这个问题上来。对于我的人。数到n=1步-1对于n=MyPeople。数到1步-1不应该只是为了n=MyPeople。数到1步-1?啊,我更喜欢while循环,对不起。编辑。
Sub RemoveEmptyUsers()
Dim RemoveDecider As Integer
RemoveDecide = 0
Dim test As Integer
test = 0
Set rng = Range("B17", Range("B65536").End(xlUp).Offset(1))
MsgBox (MyPeople.Count)
    For n = MyPeople.Count To 1 Step -1
        For Each cel In rng
            If cel.Value = MyPeople(n).SiView Then
                Exit For
            End If
            If cel.Value = 0 Then 'the last empty cell after all entries are checked for user
                MsgBox (MyPeople(n).FirstName & " has been removed")
                MyPeople.Remove (n)
                Exit For
            End If
        Next cel
    Next n
End Sub