我正在研究将电子邮件发送到收件人列表的方法。所有电子邮件都应包含相同的正文,但具有唯一的附件。我正在使用的代码成功从N列检索地址,并根据O:AZ列中相应行中的路径插入附件。
我遇到的问题是使用代码创建的第一封电子邮件没有正文。收件人和附件是正确的,但电子邮件本身是空的。创建的所有其他电子邮件都正确显示正文。我对VBA的经验很少,无法找到导致问题的原因。
有关代码和可能的问题的任何帮助将不胜感激!如果您需要有关代码或数据的更多详细信息,请与我们联系。
Sub create_emails()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range
Dim FileCell As Range
Dim rng As Range
Dim strobody As String
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet2")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("N").Cells.SpecialCells(xlCellTypeConstants) 'email addresses located in Sheet2, column N
Set rng = sh.Cells(cell.Row, 1).Range("O1:AZ1") 'File paths stored in corresponding rows, columns 0:AZ
If cell.Value Like "?*@?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
With OutMail
.SentOnBehalfOfName = "xxx@xxx.xxx"
.To = cell.Value
.Subject = "test subject"
.Body = strbody
strbody = "Test text"
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Display 'Or use .Display / .Send
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
答案 0 :(得分:0)
你在使用它之后设置了strbody,所以它第一次使用它是空的。
变化:
With OutMail
.SentOnBehalfOfName = "xxx@xxx.xxx"
.To = cell.Value
.Subject = "test subject"
.Body = strbody
strbody = "Test text"
要:
With OutMail
.SentOnBehalfOfName = "xxx@xxx.xxx"
.To = cell.Value
.Subject = "test subject"
strbody = "Test text"
.Body = strbody
此外,如果您设置了Option Explicit
,则您注意到strbody
的声明错误地输入了strobody
。