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

时间:2017-07-20 14:51:40

标签: excel vba excel-vba

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

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

我很确定问题出在我的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

2 个答案:

答案 0 :(得分:1)

你的循环应该是这样的:

<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script>
<div id="app">
  <search></search>
</div>

答案 1 :(得分:0)

这是我想出的。以上评论都属实。我需要扭转循环。如您所见,现在我从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