在使用Excel VBA发送邮件时,在Outlook中选择账户。

3
我希望能在Excel的VBA中从指定的Outlook账户发送邮件,但我的代码出现了问题。我查看了许多论坛,但是还是不能解决问题。
如果有人可以帮助我,我会非常感激。以下是我的代码:
Sub SendMail()

Dim objOutlook As Object
Dim objMail As Object
Dim ws As Worksheet

Set objOutlook = CreateObject("Outlook.Application")
Set ws = ActiveSheet
Dim signature As String
Dim LstRow As Long
LstRow = ws.Cells(Rows.Count, 1).End(xlUp).Row

Dim oAccount As Outlook.Account

For Each oAccount In Outlook.Application.Session.Accounts

If oAccount = "mymail@server.com" Then

For Each cell In ws.Range("A4:A" & LstRow)

Set objMail = objOutlook.CreateItem(0)
signature = objMail.Body
    With objMail
        .To = cell.Value
        .Subject = cell.Offset(0, 1).Value
        .Body = cell.Offset(0, 2).Value & vbNewLine & signature
        .Attachments.Add cell.Offset(0, 3).Value
        .DeferredDeliveryTime = "15/03/2018 10:00:00 PM"
        .SendUsingAccount = oAccount
        .send
    End With

    Set objMail = Nothing
Next cell
Else
End If

Next
Set ws = Nothing
Set objOutlook = Nothing

End Sub

你在哪一行出错了?你试过使用.SentOnBehalfOfName吗? - Maddy
没有错误,只是钉子没有发送。 - salom
是的,我也尝试了代表发送,但结果还是一样的。 - salom
.Send.Display在哪里? - Maddy
抱歉,这是在使用账户发送后的结果。 - salom
显示剩余12条评论
1个回答

6
解决方案就是在.SendUsingAccount前面加上Set。
 Set objMail = objOutlook.CreateItem(0)
signature = objMail.Body
   With objMail
    .To = cell.Value
    .Subject = cell.Offset(0, 1).Value
    .Body = cell.Offset(0, 2).Value & vbNewLine & signature
    .Attachments.Add cell.Offset(0, 3).Value
    .DeferredDeliveryTime = "15/03/2018 10:00:00 PM" 'need to comment here to run better
   Set .SendUsingAccount = oAccount
    .send
End With

同时感谢 Maddy,我在 deferredDeliveryTime 后面添加了注释,并且它已经成功通过 oAccount。

设置.SendUsingAccount = oAccount没有起作用,但是对于O365PP 的发送来自另一个邮箱而不是我的默认邮箱,SentOnBehalfOfName 对我起了作用。 - Timo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接