首页 > 解决方案 > VBA为什么我的循环卡在第一个项目上,在我确保它不符合标准之后

问题描述

我目前正在使用一个遍历两个数据范围的for循环 - 如果它看到第一行中的一个单元格有“拒绝”这个词并且第二行是空的,它意味着用待处理填充该单元格,然后生成退出子之前的电子邮件。

一旦你再次开始循环,它意味着找到满足这些参数的下一行。但是,它只会再次进入第一个。

我试图通过确保它用“待定”填充该单元格来否定这一点——这意味着它不再是空的,但它仍然只会到那里。

这是代码:

Dim i As Long 'Defining i, which will be used to loop through the ranges.

For i = 6 To 50000 'Setting the ranges -
    If Range("M" & i) = "Rejected" And Range("N" & i) = "" Then 'Searches through the ranges first job that the partner has rejected - and then checks as to whether the partner has issued their assessment.
        Range("O" & i) = "'Pending" 'Changes the first one that has been  to 'Pending' so it won't be picked up the next time the code is run.
        GoTo Email
    End If
Next

我真的不知道该怎么做。一旦完成一封电子邮件,我需要停止子程序,否则它可能会循环并一次创建数百个,这不仅会使系统超载,还会淹没我的收件箱。

Ps,不知道为什么我的代码格式奇怪 - 抱歉

标签: excelvbaloopslogic

解决方案


问题是您正在使用 aGoTo并且做了应该做的事情,转到...您的邮件标签。一旦到达那里,它将继续代码向下,永远不会向上,就像跳过循环一样。相反,您可以将您的电子邮件代码放入另一个过程并在必要时调用它,这样循环将继续:

Option Explicit
Sub Test()

    Dim C As Range 'this will loop through the range
    Dim LastRow As Long 'this will find the last row

    With ThisWorkbook.Sheets("MySheetName") 'change MySheetName
        LastRow = .Cells(.Rows.Count, "M").End(xlUp).Row 'last row with data on column M
        For Each C In .Range("M6:M" & LastRow) 'loop through M6 to M & last row
            If C = "Rejected" And .Cells(C.Row, "N") = vbNullString And Not .Cells(C.Row, "O") = "'Pending" Then 'vbnullstring has better performance than ""
                .Cells(C.Row, "O") = "'Pending"
                Mail C.Row
            End If
        Next C
    End With

End Sub
Sub Mail(MailRow As Long)

    'Code doing your mail

End Sub

推荐阅读