【发布时间】:2016-01-16 00:12:30
【问题描述】:
我创建了一个 VBA 宏代码来使用各种标准生成具有不同收件人、主题、邮件内容、附件等的电子邮件...
代码运行良好,但附件出现问题时除外。当宏无法在给定位置找到相关文件时,它会弹出一条消息,但不会进一步推进循环。
我的问题是,如果有人可以请看看“下一步”和“退出子”应该放在哪里,以便在不停止代码的情况下继续循环并生成“错误弹出窗口”以及“电子邮件草稿”。
提前谢谢...
请在下面找到代码...
Sub Email_Creation_Tool()
On Error GoTo ErrMsg
Dim wbk As Workbook
Dim OutApp As Object
Dim OutMail As Object, signature As String
Dim i As Range, j As Long
Dim objItem As Object
With ActiveSheet
Set i = Range("A2", Range("A2").End(xlDown))
For j = 1 To i.Rows.Count
Set OutApp = CreateObject("Outlook.Application")
If Cells(j + 1, 1).Value <> "" Then
Mailto = Cells(j + 1, 3).Value
If Mailto = "Sentence No. 1" Then
Mailto = "Friend1@abc.com"
MailSubject = Cells(j + 1, 1).Value & " Sentence No. 1"
MailBody = " Hi blah blah "
End If
If Mailto = "Sentence No. 2” Then
Mailto = "Friend2@abc.com; Friend3@abc.com"
CCTo = "CommonFriend@abc.com"
MailSubject = Cells(j + 1, 1).Value & " Sentence No. 2"
MailBody = "Hi blah blah,"
End If
If Mailto = "Sentence No. 2” Then
MailSubject = Cells(j + 1, 1).Value & " Sentence No. 3"
Mailto = "Friend2@abc.com; Friend3@abc.com"
CCTo = "CommonFriend@abc.com"
MailBody = " Hi blah blah "
End If
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(o)
With OutMail
.Display
signature = OutMail.body
With OutMail
.Subject = MailSubject
.To = Mailto
.CC = CCTo
.body = MailBody & vbNewLine & signature
Name "D:\Users\MY_PC\Desktop\" & Cells(j + 1, 1).Value & ".txt" As "D:\Users\MY_PC\Desktop\" & Cells(j + 1, 1).Value & "_trial.txt"
Attach = "D:\Users\MY_PC\Desktop\" & Cells(j + 1, 1).Value & "_trial.txt"
.Attachments.Add (Attach)
Exit Sub 'where should this be placed
On Error Resume Next 'where should this be placed
End With
Set OutMail = Nothing
Set OutApp = Nothing
End With
End If
On Error Resume Next 'where should this be placed
ErrMsg:
MsgBox ("Attachment WP" & (Cells(j + 1, 1).Value) & vbNewLine & _
"Not Found/Name Incorrect")
Next j
End With
End Sub
【问题讨论】:
标签: excel vba for-loop error-handling