循环停止工作,当值错误时不会继续

时间:2015-10-15 13:55:20

标签: excel excel-vba loops while-loop vba

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

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

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

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

2 个答案:

答案 0 :(得分:0)

您没有循环浏览所有商品,因为您的While条件取决于值。

如果你的情况更像是我< uBound(Cells)或Cells.Count -1,它将继续处理。

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

或者,如果可行,请对列表进行排序,以便首先显示所有“是”值并保持此代码不变。看起来你是故意这样做的。 :)

答案 1 :(得分:0)

您可以这样使用它(非实际代码只是原型

'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