VBA主动从循环集合中删除用户引用相同的Collection.Count

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

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

我相当肯定,问题是在我的For循环从n = 1到MyPeople.Count,因为我正在积极从MyPeople删除条目。 有34个开始,并且在29(在移除6个总数之后)时出错。 问题是我不知道如何解决这个问题。

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

码:

 Sub RemoveEmptyUsers() Dim RemoveDecider As Integer RemoveDecide = 0 Dim test As Integer test = 0 Set rng = Range("B17", Range("B65536").End(xlUp).Offset(1)) For n = 1 To MyPeople.Count 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) n = n - 1 MyPeople.Count test = test + 1 Exit For End If Next cel Next n End Sub 

你的循环应该是这样的:

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

这是我想出来的。 以上评论是真实的。 我需要扭转循环。 正如你所看到的,现在我从n = mypeople计数到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