Inserting Signature into Outlook email from Excel VBA
我正在尝试使用VBA for Excel自动处理一些电子邮件。到目前为止,一切都很好,但尝试将我的签名保留在电子邮件中。
一旦您告诉VBA创建新电子邮件,它将已经包含您的默认签名。如果您尝试
我的简单尝试是将
用于复制并重新插入签名的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 | Dim myOlApp As Outlook.Application Dim MyItem As Outlook.MailItem Dim signature As String Set myOlApp = CreateObject("Outlook.Application") Set Outmail = myOlApp.CreateItem(0) signature = Outmail.HTMLBody Outmail.HTMLBody = signature Outmail.Display |
用于显示自动插入签名的代码:
1 2 3 4 5 | Dim myOlApp As Outlook.Application Dim MyItem As Outlook.MailItem Set myOlApp = CreateObject("Outlook.Application") Set Outmail = myOlApp.CreateItem(0) Outmail.Display |
编辑:我尝试将
的HTML格式。
编辑2:代码可在我朋友的计算机上使用,而不能在我的计算机上使用
已解决。只需重新启动Outlook就可以解决它。
您可以从Signatures文件夹中读取签名文件(请记住文件夹名称已本地化),并将其与消息正文合并(您不能简单地将两个格式良好的HTML文档连接起来并获取有效的HTML文档)。您还需要注意签名样式和图像-它们必须单独处理。
您还可以显示消息(在显示消息时,Outlook用签名填充未修改的消息正文),然后读取
如果使用"赎回"是一个选项,它将公开RDOSignature对象。您可以使用其
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | set Session = CreateObject("Redemption.RDOSession") Session.MAPIOBJECT = Application.Session.MAPIOBJECT set Drafts = Session.GetDefaultFolder(olFolderDrafts) set Msg = Drafts.Items.Add Msg.To ="[email protected]" Msg.Subject ="testing signatures" Msg.HTMLBody ="<html><body>some bold message text</body></html>" set Account = Session.Accounts.GetOrder(2).Item(1) 'first mail account if Not (Account Is Nothing) Then set Signature = Account.NewMessageSignature if Not (Signature Is Nothing) Then Signature.ApplyTo Msg, false 'apply at the bottom End If End If Msg.Display |
我用以下技巧解决了该问题:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | Set myOutlook = CreateObject("Outlook.Application") Set tempMail = myOutlook.CreateItem(olMailItem) With tempMail ' Trick to preserve Outlook default signature ' MailItem need to be displayed to be"fully created" as object (maybe VBA bug) .Display HTMLBody = .HTMLBody .Close olDiscard ' --- Trick to split HTMLBody into Head and Signature --- ' Search for the position of the tag before signature bodyTag ="<body" PosBody = InStr(HTMLBody, bodyTag) pTag ="<o:p>" PosSignature = InStr(PosBody, HTMLBody, pTag) Head = Left(HTMLBody, PosSignature - 1) Signature = Right(HTMLBody, Len(HTMLBody) - PosSignature + 1) End With |
然后,您只需将HTML文本放在Head和Signature之间:
1 2 3 4 5 6 7 8 9 | Set myOutlook = CreateObject("Outlook.Application") Set myMail = myOutlook.CreateItem(olMailItem) With myMail .To = Recipients .Subject = Subject .CC = CC .HTMLBody = Head &"Here the HTML text of your mail" & Signature End With |
我认为这是一种VBA错误:如果您不使用.Display方法,则不会"完全"创建MailItem对象。
尝试放置刹车点,并在.Display方法行之前和之后查看即时窗口(Ctrl G)上的
您还可以在"本地窗口"中获得相同的简单扩展
另一种可能的解决方案是直接从Windows存储签名的目录中获取签名,并将其附加到正文中。 Microsoft MVP在此处解释了(有些冗长)的过程:https://www.rondebruin.nl/win/s1/outlook/signature.htm
剪切签名的html源(例如在编辑器或mozilla-源视图中),然后将其复制到单元格中。那么您可以将单元格的值添加到您的.htmlbody中,这将是完美的。所有其他解决方案都糟糕透了,我尝试了所有这些方法:)