You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在部分附件缺失时仍发送带多附件的Outlook邮件?

解决VBA邮件附件缺失导致发送失败的问题

原代码中只要有一个附件文件不存在,邮件就无法正常生成发送。要实现「即使只有一个有效附件也能正常发送」的需求,我们可以通过为每个附件添加单独的错误处理,或者先检查文件是否存在再添加两种方式来解决。

方法1:使用错误捕获跳过无效附件

通过临时启用错误忽略,让程序在遇到不存在的附件时跳过该操作,继续执行后续代码:

Sub Send_email_IPS()
  Dim OutApp As Object
  Dim OutMail As Object

  Set OutApp = CreateObject("Outlook.Application")
  Set OutMail = OutApp.CreateItem(0)

  With OutMail
    .To = "test@email.com"
    .CC = ""
    .BCC = ""
    .Subject = "Update " & Date & " " & Time
    .HTMLBody = "Hello " & "<br>" & "<br>" & "Please find attached latest update" & "<br>" & "<br>" & "Best Regards" & "<br>" & "<br>" & "Me"
    
    ' 逐个添加附件,遇到不存在的文件时跳过
    On Error Resume Next ' 临时启用错误忽略
    .Attachments.Add "C:\Users\testuser\Work Folders\Desktop\KB4 Reporting Macro\IPS.xlsx"
    .Attachments.Add "C:\Users\testuser\Work Folders\Desktop\KB4 Reporting Macro\IPS (St Helens).xlsx"
    On Error GoTo 0 ' 恢复默认错误处理
    
    .Display
  End With

  Set OutMail = Nothing
  Set OutApp = Nothing
End Sub

方法2:先检查文件存在性再添加(更严谨)

使用Dir函数先判断文件是否存在,仅当文件存在时才添加附件,避免触发错误:

Sub Send_email_IPS()
  Dim OutApp As Object
  Dim OutMail As Object
  Dim attachmentPath As String
  
  Set OutApp = CreateObject("Outlook.Application")
  Set OutMail = OutApp.CreateItem(0)

  With OutMail
    .To = "test@email.com"
    .CC = ""
    .BCC = ""
    .Subject = "Update " & Date & " " & Time
    .HTMLBody = "Hello " & "<br>" & "<br>" & "Please find attached latest update" & "<br>" & "<br>" & "Best Regards" & "<br>" & "<br>" & "Me"
    
    ' 检查第一个附件
    attachmentPath = "C:\Users\testuser\Work Folders\Desktop\KB4 Reporting Macro\IPS.xlsx"
    If Dir(attachmentPath) <> "" Then
      .Attachments.Add attachmentPath
    End If
    
    ' 检查第二个附件
    attachmentPath = "C:\Users\testuser\Work Folders\Desktop\KB4 Reporting Macro\IPS (St Helens).xlsx"
    If Dir(attachmentPath) <> "" Then
      .Attachments.Add attachmentPath
    End If
    
    .Display
  End With

  Set OutMail = Nothing
  Set OutApp = Nothing
End Sub

关键说明

  • 方法1适合快速修改,通过错误捕获跳过无效操作,但无法直观知道哪个附件缺失;
  • 方法2更严谨,能明确控制只添加存在的文件,还可以根据需要添加日志记录缺失的附件路径。

内容的提问来源于stack exchange,提问作者Pawel Cw

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 15:15:42