2015-10-15 91 views
0

我正在创建用于发送电子邮件的代码。该程序将在每一行进行循环,并检查第一列中的值是否为“是”,然后发送电子邮件。当值错误时,循环停止工作并不会继续

当每行中的值为“是”时,程序似乎很有效,但是当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 
+0

那是因为你正在使用'While'。当它遇到非yes值的单元格时,循环将终止。因此,其余行不会被处理。使用'do while true'并添加'if(Cells((i + 1),1).value)<>“yes”'然后退出do'。也就是说,你的代码需要在很多层面上进行修正。 – shahkalpesh

+0

对于shahkalpesh关于需要更多更正的观点,请尽量避免在循环内重新创建Outlook对象。创建一次。另一方面,我假设你想更改emailto和ccto INSIDE循环,然后将.To和.cc设置为这些值。 我不确定.Display会很好 - 它只是打开一堆电子邮件窗口。我假设你会想要这样做。发送完成测试后?不是VB.NET的 –

+0

。 – Plutonix

回答

0

你是不是通过所有项目的循环,因为你虽然条件取决于值。

如果你的While条件更像我的< uBound(Cells)或Cells.Count -1,它会继续处理。

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

或者,如果可行,请对您的列表进行排序,以便所有的Yes值都是第一个,并保留原来的代码。它会看起来像你故意做的。 :)

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