编辑来自excel的打开电子邮件

时间:2018-10-01 18:24:42

标签: excel vba outlook

编辑:谢谢大家。所有建议都可能有效。我终于意识到,我的雇主启用了一个安全选项来阻止此类操作。不幸的是,我无法编辑电子邮件,只能创建它们。

我正在尝试找出如何从excel修改打开的电子邮件。

我有一个电子邮件模板,excel可以用工作簿中工作表中的值替换某些字符串。

我一直在研究 activeinspector ,但是我仍然不确定excel和Outlook之间的交叉编程如何工作。搜索各种站点可以使我得到这个信息,但是它不起作用。

  

str = OutlookMail.Body上的错误287

' Create the outlook object
Dim outlookApp As Outlook.Application
Set outlookApp = New Outlook.Application

Dim outlookInspector As Outlook.Inspector
Dim outlookMail As Outlook.MailItem

Set outlookInspector = outlookApp.ActiveInspector

Dim str As String

If Not outlookInspector Is Nothing Then
    If TypeOf outlookInspector.CurrentItem Is Outlook.MailItem Then
        Set outlookMail = outlookInspector.CurrentItem
        str = outlookMail.Body

        ' Replacements
        str = Replace(str, "DIPOC", "string1")
        str = Replace(str, "REFNUM", "string2")
        str = Replace(str, "RCVDATE", "string3")
        str = Replace(str, "EMPNAME", "string4")
        str = Replace(str, "EMPEIDN", "string5")
        str = Replace(str, "ACTIONREQ", "string6")

        outlookMail.Body = str
    End If
End If

我对此还很陌生,因此我们将不胜感激。预先谢谢你。

4 个答案:

答案 0 :(得分:1)

如果没有活动的电子邮件打开(此处没有错误处理代码),此操作将失败,但仅出于测试目的,它对我有用。我假设dipoc,RefNum,rcvdate是您在其他地方定义的变量(我使用静态字符串对其进行了测试)。此外,Outlook对象的名称为“ Outlook”,因此最好避免将对象命名为“ Outlook”。如果电子邮件中有HTML格式(如签名),则要使用.HTMLBody而不是.Body

Count

答案 1 :(得分:1)

Dim Outlook As Object
Set Outlook = CreateObject("Outlook.Application")

Dim oInspector As Inspector
Dim olOutMail As MailItem

如果代码可以编译,那么您将引用Outlook对象模型,并且Outlook标识符引用Outlook类型库:Dim Outlook As Object shadowing 声明。重命名它,并使用它们来自的库显式限定类型:

Dim outlookApp As Outlook.Application
Set outlookApp = New Outlook.Application

Dim outlookInspector As Outlook.Inspector
Dim outlookMail As Outlook.MailItem

我不能为您的前缀找到一个一致的方案,所以我删除了它。

现在,当您分配检查员参考时:

Set oInspector = Outlook.ActiveInspector

这是模棱两可的,至少对于人类读者而言是这样:如果在键入.点时得到 IntelliSense ,则VBA会将Outlook理解为Outlook.Application ,这意味着麻烦,现在您有了一个隐式Application引用,这不是您要使用的实例 ...,这很可能说明您为什么收到此错误

您要消除歧义。

Set outlookInspector = outlookApp.ActiveInspector

这应该给您提供您打算使用的Inspector参考。

下一个问题是,您设置olOutMail对象引用假设有一个活动的检查器,而您正在查看的是MailItem-如果有任何假设,都将引发火灾不是真的。

If Not outlookInspector Is Nothing Then
    If TypeOf outlookInspector.CurrentItem Is Outlook.MailItem Then
        'NOW we KNOW we're looking at a mailitem.
        Set outlookMail = outlookInspector.CurrentItem
        '...work with outlookMail here...
    End If
End If

答案 2 :(得分:0)

您正在初始化olOutMail变量,然后再初始化oInspector变量。 切换它们:

Set oInspector = Outlook.ActiveInspector
Set olOutMail = oInspector.CurrentItem

答案 3 :(得分:0)

从我的角度来看它运行良好。它将我的电子邮件更改为纯文本格式。

这是我的测试环境:Office 2016 + Windows 10及以下版本是我测试过的代码。

print(age + " " + house + " " + reactionTime)

最好的问候,

埃文