以下是我用来通过Outlook将电子邮件发送到电子邮件地址列表的Excel VBA代码。每个电子邮件地址都有一个需要发送的不同附件。我需要在此代码中进行哪些错误处理。现在,所有代码所做的就是在执行电子邮件处理之前检查文件是否全部存在。
电子邮件列表从A2开始在A栏,要附加的文件从B2开始在B栏。文件的文件夹路径为E11,电子邮件主题行为E12,电子邮件正文位于Excel TextBox中。
Sub Loop1()
Dim Body As String, I As Integer, filePath As String, fs
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
'Create Outlook Session
Set objOutlook = CreateObject("Outlook.Application")
Range("A2").Select
StartRow = ActiveCell.Row
EndRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
Set fs = CreateObject("Scripting.FileSystemObject")
Body = ActiveSheet.Shapes.Range(Array("TextBox 1")).TextFrame2.TextRange.Characters.Text
For I = StartRow To EndRow
filePath = Range("E1").Value & "\" & Range("B" & I).Value
If Not fs.FileExists(filePath) Then
Range("B" & I).Select
MsgBox ("The file " & vbCrLf & filePath & vbCrLf _
& " in Cell B" & I & " does not exist" _
& vbCrLf & "The macro is cancelled")
End
End If
Next I
For I = StartRow To EndRow
filePath = Range("E1").Value & "\" & Range("B" & I).Value
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
.Recipients.Add (Range("A" & I).Value)
.Subject = Range("E2").Value
.Body = Body
.Attachments.Add (filePath)
.Save
.Send
End With
Set objOutlookMsg = Nothing
Next I
Set objOutlook = Nothing
Set fs = Nothing
End Sub
最佳答案
除了可能发生的情况外,我真的不能说您应该“测试”什么。作为用户,获得帮助我了解问题所在的消息总是更好,更好,因此我可以确定是否可以修复它。获取VBA的标准“结束”或“调试” pop 窗口根本对最终用户没有帮助...只能帮助开发人员...
以下是您要测试的一些想法:
这远不是可以测试的所有内容,但是您必须对在何处编写额外代码进行自己的风险分析。
关于vba - 带有不同附件的VBA电子邮件合并的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22283693/