【问题标题】:How can I ignore an email attachment if missing from folder如果文件夹中缺少电子邮件附件,我该如何忽略
【发布时间】:2019-01-03 16:22:25
【问题描述】:

我有两件事需要修改

我目前有代码从 A 列提取电子邮件地址并附加 3 个在 BC 和 D 列中标识的文件。但是 D 列中的文件并不总是存在,如果不存在,我希望代码忽略它们成立。

另外,邮件可以包含用户的标准签名吗?

Sub email1()

Dim OutLookApp As Object
Dim OutLookMailItem As Object
Dim lastRow As Long
Dim MailDest As String
Dim subj As String

lastRow = ThisWorkbook.Worksheets("sheet1").Cells(Rows.Count, "A").End(xlUp).Row 'change worksheet


If fileExists("g:\test\", Cells(i, 2).Value & ".xls") Then
For i = 2 To lastRow

Set OutLookApp = CreateObject("Outlook.application")
Set OutLookMailItem = OutLookApp.CreateItem(0)
Set Attach = OutLookMailItem.Attachments

With OutLookMailItem
.SentOnBehalfOfName = " test@test.co.uk "
    .To = Cells(i, 1).Value
    '.cc = "test@test.co.uk"
    .Subject = Cells(i, 6).Value
    .Body = Cells(i, 7).Value
 Attach.Add " g:\test\", \" & Cells(i, 2).Value & ".xls"
            .Display 'for debugging
    SendKeys "^{ENTER}"
  End If
End With
SendKeys "^{ENTER}"
Next
MsgBox ("Emails have all been Sent Successfully")
End Sub

【问题讨论】:

  • 您是否尝试过查看是否可以分配.From 地址?在尝试附加之前验证 Dir("f:\test\" & Cells(i, 2).Value & ".xls") 是否返回空字符串?
  • 也许有一些建议 - 1. 关于 SO 的问题将回答如何从共享邮箱发送,以及如何使用您的签名填充电子邮件。 2. 将Set OutlookApp = ... 移出你的循环,因为你只需要做一次。
  • From 已被纠正,我正在努力解决其他 2 个问题
  • 感谢所有帮助,我现在正在尝试创建另一个仅在特定文件存在时生成电子邮件的模块。 ?

标签: excel vba


【解决方案1】:

你有没有试过把它包装成一个条件 if 'fileExists' 或类似的东西......

If fileExists("f:\test", Cells(i, 4).Value & ".xls") Then 
     Attach.Add "f:\test\" & Cells(i, 4).Value & ".xls"
End If

然后创建函数来测试文件是否存在。

Function fileExists(s_directory As String, s_fileName As String) As Boolean
    Dim obj_fso As Object
    Set obj_fso = CreateObject("Scripting.FileSystemObject")
    fileExists = obj_fso.fileExists(s_directory & "\" & s_fileName)
End Function

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2012-09-18
    • 2020-05-25
    • 2018-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-15
    相关资源
    最近更新 更多