我的VBA代码在列“I”中循环显示人名,并创建一个电子邮件列表。在电子邮件正文中,列B,C,G,I中每个人都有一个行的列表。非常简单,但是我遇到了后者的问题。它只需要每个人的第一行,即不循环列表以获得一个收件人的所有行。 我有一种感觉,这在某种程度上阻止它进一步循环:在Excel VBA中循环显示多列的问题
If InStr(1, PriorRecipients, EmailAddr) <> 0 Then
GoTo NextRecipient
End If
,但不知道如何实现第二个循环?
全码:
Sub SendEmail2()
Dim OutlookApp
Dim MItem
Dim cell As Range
Dim Subj As String
Dim EmailAddr As String
Dim Recipient As String
Dim Msg As String
Dim Projects As String
Dim ProjectsMsg As String
Dim bSendMail As Boolean
'Create Outlook object
Set OutlookApp = CreateObject("Outlook.Application")
Set MItem = OutlookApp.CreateItem(0)
'Loop through the rows
For Each cell In Columns("I").Cells.SpecialCells(xlCellTypeVisible)
If cell.Value <> "" And _
(Cells(cell.Row, "L").Value) = "No" And (Cells(cell.Row, "K").Value) <> "Yes" Then
'first build email address
EmailAddr = LCase$(Replace(cell.Value, " ", ".")) & "@company.com"
'then check if it is in Recipient List build, if not, add it, otherwise ignore
If InStr(1, Recipient, EmailAddr) = 0 Then Recipient = Recipient & ";" & EmailAddr
Projects = vbCrLf & "Document: " & Cells(cell.Row, "B").Value & "; " & Cells(cell.Row, "C").Value & "; " & "Rev " & Cells(cell.Row, "G").Value & "; " & Cells(cell.Row, "I").Value
If InStr(1, ProjectsMsg, Projects) = 0 Then ProjectsMsg = ProjectsMsg & Projects & vbCrLf
If InStr(1, Recipient, cell.Offset(1).Value) <> 0 Then
bSendMail = True
Recipient = Recipient & ";" & cell.Offset(1)
Else
bSendMail = False
End If
End If
Next
Msg = "You have the following outstanding documents to be reviewed at: "& ProjectsMsg
Subj = "Outstanding Documents to be Reviewed"
'Create Mail Item and view before sending
If bSendMail Then Set MItem = OutlookApp.CreateItem(olMailItem)
With MItem
.To = Recipient 'full recipient list
.Subject = Subj
.Body = Msg
.display
End With
End Sub
尝试如果语句之前分配PriorRecipients,然后用另一个变量之后重新分配。它看起来好像在第一个循环中有PriorRecipients的字符串值,这会导致错误。 – Dan
@丹 你的意思只是一个简单的 PriorRecipients =“”之前如果 并重新分配一个新的变量之后if?是,而不是PriorRecipients = PriorRecipients & ";“&EmailAddr? – warfo09
是的,如果你通过你的循环,你可以看到它用于第一个if语句的preprerecipient的值,如果它有一个空值,你需要分配它在if语句前让它正常运行 – Dan