SentOnBehalfOf无法在Excel 2010 VBA代码中使用

时间:2014-10-17 19:37:47

标签: excel vba excel-vba outlook-vba outlook-2010

我正在开发一个VBA脚本,用于在Excel 2010中通过Outlook进行邮件发送。一切正常,只有一个例外:.SentOnBehalfofName行无效。这是完整的代码

 Sub Mail()
' Working in Office 2010-2013
    Dim OutApp As Outlook.Application
    Dim OutMail As Outlook.MailItem
    Dim strbody As String ' This is for the Body of the email
    Dim signature As String ' This is for the email signature

On Error Resume Next

'Set OutMail = Nothing
'Set OutApp = Nothing


Dim sh As Worksheet
Set sh = Sheets("Mail")
strbody = sh.Range("C9").Value


Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
    With OutMail ' This inserts the email signature
        .Display
    End With
       signature = OutMail.HTMLBody

With OutMail
    '.Display
    .To = sh.Range("C5")
    .CC = sh.Range("C6")
    .BCC = sh.Range("C7")
    .Subject = sh.Range("C8").Value
    .HTMLBody = "<br>" & strbody & fncRangeToHtml(sh.Range("C13").Value, sh.Range("C14").Value) & signature
    .SentOnBehalfOfName = sh.Range("C4").Value
    .Display

End With

On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing

 End Sub

如果删除此部分,.SentOnBehalfOf可以正常工作,但我丢失了我的签名行:

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
    With OutMail ' This inserts the email signature
        .Display
    End With
       signature = OutMail.HTMLBody

如果我把它放回代码中,我会回复我的签名行,但是我失去了代表另一方发送的能力。

我正在寻找一种允许我同时做到这一点的解决方案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:1)

这是我的解决方案。我需要将.SentOnBehalfOfName移动到WITH命令中的第一个语句,然后立即显示.Display。我用.HTMLBody替换签名行的字符串以拉入签名行。代码运行正常!

我不知道为什么声明需要按此顺序排列,但它有效.......

Sub Mail()
' Working in Office 2010-2013
Dim OutApp As Outlook.Application
Dim OutMail As Outlook.MailItem
Dim strbody As String ' This is for the Body of the email

On Error Resume Next

'Set OutMail = Nothing
'Set OutApp = Nothing

Dim sh As Worksheet
Set sh = Sheets("Mail")
strbody = sh.Range("C9").Value


Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
    .SentOnBehalfOfName = sh.Range("C4")
    .Display
    .To = sh.Range("C5")
    .CC = sh.Range("C6")
    .BCC = sh.Range("C7")
    .Subject = sh.Range("C8").Value
    .HTMLBody = "<br>" & strbody & fncRangeToHtml(sh.Range("C13").Value, sh.Range("C14").Value) & .HTMLBody

End With

On Error GoTo 0

Set OutMail = Nothing
Set OutApp = Nothing

End Sub