Reputation: 1040
I need to open and read .eml files using VBA. Shockingly this seems to be difficult. Please help. The below code gives this error at line Set OL = GetObject("Outlook.Application")
:
Run-time error '-2147221020 (800401e4)': Automation error Invalid Syntax
Code:
Private Declare Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long
Private Const SW_SHOWNORMAL As Long = 1
Private Const SW_SHOWMAXIMIZED As Long = 3
Private Const SW_SHOWMINIMIZED As Long = 2
Sub test11()
strMyFile = "C:\test.eml"
Dim Myinspect As Outlook.Inspector
Dim MyItem As Outlook.MailItem
Dim OL As Object
If Dir(strMyFile) = "" Then
MsgBox "File " & strMyFile & " does not exist"
Else
ShellExecute 0, "Open", strMyFile, "", "C:\test1.eml", SW_SHOWNORMAL
End If
Set OL = GetObject("Outlook.Application")
Set Myinspect = OL.ActiveInspector
Set MyItem = Myinspect.CurrentItem
MsgBox "Subject = " & MyItem.Subject
MsgBox "Body = " & MyItem.Body
MyItem.Close 1
End Sub
Upvotes: 0
Views: 7637
Reputation: 53663
The GetObject
function takes the class name as second argument:
Set OL = GetObject(, "Outlook.Application")
It's CreateObject
which would take it first:
Set OL = CreateObject("Outlook.Application")
Note that Outlook will only run one instance, ever. You should be able to call the CreateObject
function and would not need to use GetObject
. If Outlook is already open, CreateObject
will return that instance, if outlook is not already open, it will create one.
Upvotes: 1