Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open Outlook Mail .msg file using VBA from Excel

Tags:

excel

vba

outlook

I'm trying to open .msg files from a specified directory using VBA but I keep getting a runtime error.

The code i have:

Sub bla()
    Dim objOL As Object
    Dim Msg As Object
    Set objOL = CreateObject("Outlook.Application")
    inPath = "C:\Users\SiliconPlus\Desktop\Si+ Contact Lists\Contact_Si+"
    thisFile = Dir(inPath & "\*.msg")
    Set Msg = objOL.CreateItemFromTemplate(thisFile)
    ' now use msg to get at the email parts
    MsgBox Msg.Subject
    Set objOL = Nothing
    Set Msg = Nothing
End Sub

Here is the runtime error:

Run-time error '-2147287038 (80030002)':

Cannot open file: AUTO Andy Low Yong Cheng is out of the office (returning 22 09 2014).msg.

The file may not exist, you may not have permission to open it, or it may be open in another program. Right-click the folder that contains the file, and then click properties to check your permissions for the folder.

like image 664
Kenneth Li Avatar asked Jun 18 '15 07:06

Kenneth Li


People also ask

Can VBA interact with Outlook?

If you are using VBA to create macros, there are two ways you can automate Outlook. You can implement a macro that creates a new instance of the Outlook Application object. The CreateNewDefaultOutlookTask() method above shows how to call New Outlook. Application to create a new Application object instance.

How do I use Excel VBA with Outlook?

Step 1: In the Developer Tab click on Visual Basic to open the VB Editor. Step 2: Go to Tools and then select References as shown in the below screenshot. Step 3: Scroll down in the Reference Object library and select “Microsoft Outlook 16.0 Object Library” to make it available for Excel VBA.

How do I open attachments in Outlook VBA?

Save and Open Attachments VBA Sample To use this code sample, open the VBA editor by pressing Alt+F11 keys. Paste the code into the ThisOutlookSession module. If it does not exist, create the directory path on your hard drive then update the code with the path. Select one or more attachments and run the macro.


1 Answers

Kenneth Li You didn't had the full path when opening the file. Try this:

Sub bla_OK()
Dim objOL As Object
Dim Msg As Object
Set objOL = CreateObject("Outlook.Application")
inPath = "C:\Users\SiliconPlus\Desktop\Si+ Contact Lists\Contact_Si+"
thisFile = Dir(inPath & "\*.msg")
'Set Msg = objOL.CreateItemFromTemplate(thisFile)
Set Msg = objOL.Session.OpenSharedItem(inPath & "\" & thisFile)
' now use msg to get at the email parts
MsgBox Msg.Subject
Set objOL = Nothing
Set Msg = Nothing
End Sub
like image 188
Miguel Avatar answered Nov 10 '22 01:11

Miguel