【问题标题】:Loop stops working and does not continue when the value is wrong循环停止工作,当值错误时不继续
【发布时间】:2026-01-23 08:05:04
【问题描述】:

我正在创建用于发送电子邮件的代码。该程序将在每一行中循环并检查第一列中的值是否为“是”,然后发送电子邮件。

当每一行的值为“yes”时,该程序似乎运行良好,但是当有 1 行为空或具有其他值而不是“yes”时,即使仍有一些行包含“yes”,它也会停止循环在该特定行下。

如果有人可以帮助我,我将不胜感激

Sub SendMail()


Dim i As Integer


    i = 2

emailto = Cells((i + 1), 2).Text
    ccto = Cells((i + 1), 3).Text


While (Cells((i + 1), 1).value) = "yes"

Set outapp = CreateObject("Outlook.Application")
Set outmail = outapp.CreateItem(0)


With outmail
    .To = emailto
    .cc = ccto
    .BCC = ""
    .subject = "Subject"
    .Body = "bodytext"
    .Display
End with

   i = i + 1

Wend

Set outmail = Nothing
Set outapp = Nothing

End Sub

【问题讨论】:

  • 那是因为你使用的是While。循环将在遇到值不是 yes 的单元格时终止。因此,您的其余行不会被处理。使用do while true 并添加if (Cells((i + 1), 1).value) <> "yes" 然后退出do`。也就是说,您的代码需要在多个级别上进行更正。
  • 为了 shahkalpesh 关于需要更多更正的观点,请尽量避免在循环内重新创建 Outlook 对象。创建一次。另一方面,我假设您想在循环内更改 emailto 和 ccto,然后将 .To 和 .cc 设置为这些值。我不确定 .Display 会不会很好——它只会打开一堆乱七八糟的电子邮件窗口。我假设您会希望它在完成测试后发送?

标签: excel loops while-loop vba


【解决方案1】:

您没有遍历所有项目,因为您的 While 条件取决于值。

如果您的 While 条件更像 i

您可能需要考虑 FOR 或 FOR EACH 循环而不是 WHILE。

或者,如果可行,请对您的列表进行排序,以使所有 Yes 值都排在第一位,并保持此代码不变。看起来你是故意的。 :)

【讨论】:

    【解决方案2】:

    您可以这样使用它(不是实际代码,只是一个原型

    'A loop to process through all rows of the table (For/Foreach)
    'table.rows (depends upon your table type) (a datatable or whatever mode you are using)
    For i=0 to table.rows-1 
        ' check for the field containing 'yes'
        If Cells((i + 1), 1).value) = "yes" Then
            'use continue to skip this record and continue with the next one
            Continue
        Else
            ' Process your e-mail
        End If
    Next
    

    【讨论】: