如何打开 .msg 文件?

How to open a .msg file?

我想打开一个 .msg 文件。

我无法像打开工作簿那样打开 .msg 文件。

Sub OpenMail()
    
    Workbooks("MyBook").Sheets("Sheet1").Activate

    Dim MyItem1 As Outlook.MailItem
    Dim MyItem2 As Outlook.MailItem

    If Range("A1").Value > 0 Then 
        Set MyItem1.Open = "C:\Users\jeff\OneDrive\Documents\Email #1.msg"
        MyItem1.Display

    Else If Range("A1").Value < 0 Then
        Set MyItem2.Open = "C:\Users\jeff\OneDrive\Documents\Email #2.msg"
        MyItem2.Display
    Else 
        MsgBox("No items to open")

    End If

End Sub

它给了我

Run-time error 91
Object variable or With block variable not set

我在参考库中连接了 Outlook(在工具下)。

您需要先创建 Outlook 对象本身,然后使用它打开邮件。

您"Set" Mailitem 将成为新打开的邮件:

Public Sub foo()

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

Dim MyItem1 As Outlook.MailItem
Dim MyItem2 As Outlook.MailItem

Workbooks("MyBook").Sheets("Sheet1").Activate

If Range("A1").Value > 0 Then

      Set MyItem1 = objOL.Session.OpenSharedItem("C:\Users\jeff\OneDrive\Documents\Email #1.msg")

      MyItem1.Display

ElseIf Range("A1").Value < 0 Then
      Set MyItem2 = objOL.Session.OpenSharedItem("C:\Users\jeff\OneDrive\Documents\Email #2.msg")
        MyItem2.Display
Else
      MsgBox ("No items to open")

End If

set objOL = Nothing

End Sub

另外请注意,ElseIf 语句中没有 space(虽然这可能只是复制和粘贴问题)。

希望对您有所帮助!

改为尝试将物体调暗。此外,您可能需要将 Outlook 会话设置为在已打开的情况下引用 Outlook,或者在尚未打开的情况下打开 Outlook。

Dim oApp As Object
Dim oItem1 As Object
Dim oItem2 As Object

Set oApp = CreateObject("Outlook.Application")
'oApp.Session.Logon -> if needed, uncomment

Set oItem1 = oApp.CreateItemFromTemplate("C:\test1.msg")
Set oItem2 = oApp.CreateItemFromTemplate("C:\test2.msg")

'Condition
'if true
oItem1.Display 
'else
oItem2.Display
'end if

End Sub