VBA 自动发送电子邮件

问题描述 投票:0回答:1

我是 VBA 初学者。我想创建一个 VBA 脚本,可以帮助我向我的同事发送数百封带有不同附件的电子邮件。我本周已经尝试并写下了一些代码,当附件存在时这些代码将起作用。但是,如果在文件夹中找不到确切的附件,代码将显示错误并且无法运行。

我的目标是,如果附件不存在,则将其跳到下一列,直到该列附件确实存在于文件夹中,然后起草电子邮件。如果有人能帮助我,我非常感激。

这是我的代码:


Sub autoSendingbill()

Dim openoutlook As Outlook.Application
Set openoutlook = New Outlook.Application

Dim newMail As MailItem
Dim secCol, totalCol As Integer
totalCol = Cells(1000, 1).End(xlUp).Row

For secCol = 2 To totalCol
Set newMail = openoutlook.CreateItemFromTemplate("D:\AutoSendingBill.oft")

    With newMail
        .To = Cells(secCol, 2).Value
        .Subject = "Internet Service Monthly Fee"
        .HTMLBody = Replace(.HTMLBody, "Name", Cells(secCol, 1).Value)
        .HTMLBody = Replace(.HTMLBody, "Code", Cells(secCol, 4).Value)
        .HTMLBody = Replace(.HTMLBody, "ISP", Cells(secCol, 5).Value)
        .Attachments.Add Cells(secCol, 3).Value
        .Close olSave
    End With
    Next secCol
End Sub


excel vba automation outlook
1个回答
0
投票

您可以检查文件是否存在:

if (Dir(Cells(secCol, 3).Value) <> "") Then
  .Attachments.Add Cells(secCol, 3).Value
End If

或者(如果文件存在但无法读取)捕获异常:

On Error Resume Next
.Attachments.Add Cells(secCol, 3).Value
If Err.Number <> 0 Then
    MsgBox "An error occurred: " & Err.Description
    ' Reset the Err object
    Err.Clear
End If

' Disable error handling
On Error Goto 0
© www.soinside.com 2019 - 2024. All rights reserved.