I want to open a .msg file.
I can't open .msg files as I would workbooks.
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
It gives me
Run-time error 91
Object variable or With block variable not set
I connected Outlook in Reference Library (under Tools).
You need to create the Outlook object itself first and then use it to open the message.
You "Set" the Mailitem to then be the newly opened message:
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
Also just as a note there isn't a space in the ElseIf statement (that may have just been a copy and paste issue though).
Hope this helps!