导出Outlook电子邮件内容到Excel

时间:2015-10-20 13:04:32

标签: excel vbscript outlook

我收到的格式如下:enter image description here

我使用了某人在其他主题中消化的代码。这是代码:

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.NameSpace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String
    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xlsx")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
     Dim MyAr() As String

         MyAr = Split(olMail.Body, vbCrLf)

         For i = LBound(MyAr) To LBound(MyAr)
        '~~> This will give you the contents of your email
        '~~> on separate lines
         Debug.Print MyAr(i)
         Next i
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("D" & lRow).Value = olMail.Subject
        .Range("A" & lRow).Value = olMail.SenderName
        .Range("C" & lRow).Value = olMail.Body
        .Range("B" & lRow).Value = olMail.ReceivedTime
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

我想将电子邮件的内容,主题,接收时间,发件人导出到Excel文件中。我设法导出所有这些字段,但我的电子邮件内容有问题。所有这些数字都放在一个单元格中。以下是导出内容的方式:enter image description here

以下是我想要的内容:enter image description here

或者像这样: enter image description here

1 个答案:

答案 0 :(得分:1)

Outlook对象模型提供了三种使用项主体的主要方法:

  1. Body - 表示Outlook项目的明文正文的字符串。
  2. HTMLBody - 表示指定项目的HTML正文的字符串。
  3. Word editor - 正在显示的消息的Microsoft Word文档对象模型。 WordEditor类的Inspector属性从Word对象模型返回Document类的实例,您可以使用它来设置消息正文。
  4. 您可以在Chapter 17: Working with Item Bodies中详细了解所有这些方式。我们取决于你选择解析消息体的方式。