使用VBA打开并读取.eml文件

时间:2015-02-18 15:52:41

标签: vba parsing eml

我需要使用VBA打开并读取.eml文件。令人震惊的是,这似乎很难。请帮忙。以下代码在第Set OL = GetObject("Outlook.Application")行提供此错误:

  

运行时错误' -2147221020(800401e4)':   自动化错误   语法无效

代码:

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

1 个答案:

答案 0 :(得分:1)

GetObject函数将类名作为第二个参数:

Set OL = GetObject(, "Outlook.Application")

CreateObject首先采用它:

Set OL = CreateObject("Outlook.Application")

请注意,Outlook将只运行一个实例。您应该可以调用CreateObject函数,而不需要使用GetObject。如果Outlook已经打开,CreateObject将返回该实例,如果outlook尚未打开,它将创建一个。