2

如果我收到来自特定地址的具有特定主题的电子邮件,我正在运行以下脚本。目标是使用超链接标记电子邮件,该超链接将有助于所述电子邮件的收件人在原始邮件正文中拥有。

Option Explicit
Sub Megatron(MyMail As MailItem)
Dim objOL As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim strID As String
Dim strLink As String
Dim strNewText As String
Dim strLinkText As String

'On Error Resume Next
Set objOL = Application
strID = MyMail.EntryID
Set MyMail = Application.Session.GetItemFromID(strID)
If Not MyMail Is Nothing Then
    Set objNS = objOL.Session
    MyMail.BodyFormat = olFormatHTML
    If MyMail.BodyFormat = olFormatHTML Then
    MsgBox ("set to html")
    End If

    strLink = "http://www.example.com"
strLinkText = "Click on this Example!"
strNewText = "<p><a href=" & Chr(34) & strLink & _
         Chr(34) & ">" & strLinkText & "</a></p>"
MyMail.HTMLBody = Replace(MyMail.HTMLBody, "</body>", _
                      strNewText, 1, 1, vbTextCompare)
    MyMail.Save     
    MsgBox ("Hyperlink appended!")
Else
MsgBox ("Failure!")
End If
End Sub

当我收到消息框告诉我发生了正确的事件时,似乎没有进行任何实际更改(或者没有正确保存?)。

这是我对任何类型的编程所做的第一项工作。我已经阅读了一些专门针对 VB 的教程,但我对此很陌生。非常感谢任何帮助/指导!

4

1 回答 1

3

这是需要使用Option Explicit来要求显式变量声明的经典案例。使用它,因为您正在学习 VBA。还要避免使用的习惯,On Error Resume Next因为这会忽略所有错误处理。

您可能没有意识到这一点,但您通过以下方式引用您的邮件:

  • 我的邮件
  • 对象项
  • 对象消息
  • 对象邮件

注意以下两个命令

objMsg.HTMLBody

objMail.Save

在不存在的对象上执行。

去掉上面三个额外的引用:

Sub Megatron(MyMail As MailItem)
Dim objOL As Outlook.Application
Dim objNS As Outlook.NameSpace
Dim objItem As Object
Dim strID As String
Dim strLink As String
Dim strNewText As String
Dim strLinkText As String
strLink = "http://www.example.com"
strLinkText = "Click on this Example!"
strNewText = "<p><a href=" & Chr(34) & strLink & _
         Chr(34) & ">" & strLinkText & "</a></p>"
MyMail.HTMLBody = Replace(MyMail.HTMLBody, "</body>", _
                      strNewText, 1, 1, vbTextCompare)
MyMail.Save
end Sub

你也不需要清理。

于 2013-09-04T19:22:17.720 回答