【问题标题】:Identifying Outlook mail with specific subject from Excel从 Excel 中识别具有特定主题的 Outlook 邮件
【发布时间】:2018-07-18 03:37:39
【问题描述】:

我有以下代码用于从 Outlook 电子邮件中提取表格。

它只查看最新的电子邮件。我需要在电子邮件的主题中匹配一个字符串来确定要从哪封电子邮件中提取。

我需要在代码中添加什么?

Option Explicit

Sub impOutlookTable()

Dim wkb As Workbook
Set wkb = Workbooks.Add

Sheets("Sheet1").Cells.ClearContents

' point to the desired email
Const strMail As String = "first.last@outlook.com"

Dim oApp As Outlook.Application
Dim oMapi As Outlook.MAPIFolder
Dim oMail As Outlook.MailItem

On Error Resume Next
Set oApp = GetObject(, "OUTLOOK.APPLICATION")
If (oApp Is Nothing) Then Set oApp = CreateObject("OUTLOOK.APPLICATION")

On Error GoTo 0

Set oMapi = oApp.GetNamespace("MAPI").Folders(strMail).Folders("inbox")
Set oMail = oMapi.Items(oMapi.Items.Count)

' get html table from email object
Dim oHTML As MSHTML.HTMLDocument: Set oHTML = New MSHTML.HTMLDocument
Dim oElColl As MSHTML.IHTMLElementCollection
With oHTML
    .Body.innerHTML = oMail.HTMLBody
    Set oElColl = .getElementsByTagName("table")
End With

'import in Excel
Dim x As Long, y As Long
For x = 0 To oElColl(0).Rows.Length - 1
    For y = 0 To oElColl(0).Rows(x).Cells.Length - 1
        Range("A1").Offset(x, y).Value = oElColl(0).Rows(x).Cells(y).innerText
    Next y
Next x

Set oApp = Nothing
Set oMapi = Nothing
Set oMail = Nothing
Set oHTML = Nothing
Set oElColl = Nothing

wkb.SaveAs "C:\Users\user\.spyder-py3\Outlook\tables.xlsx"

End Sub

【问题讨论】:

    标签: excel vba outlook


    【解决方案1】:

    如果您只想检索一封指定主题的电子邮件:

    If oMapi.Items.Item(i).Subject = "Your subject here" Then 
    
    'Some code here
    
    End if
    

    如果你想检索所有指定主题的邮件:

    For i = 1 To oMapi.Items.Count 
      If oMapi.Items.Item(i).Subject = "Your subject here" Then 
        'Some code here 
      End If 
    Next i
    

    我还没有测试过它,但它会在某个地方,你可以看到Microsoft Online documentation for more information

    【讨论】:

    • 我只寻找一封与主题匹配的电子邮件。我将第一个选项放在以下代码之后:Set oMail = oMapi.Items(oMapi.Items.Count)。但是,它似乎只查看最后一封与主题匹配的电子邮件。我需要它查看整个收件箱,然后从匹配的电子邮件中提取表格(无论是否是最后一封)
    • 第一个选项只检查是否满足条件,如果满足,则执行 if 和 end if 之间的代码。您可能想要测试迭代所有电子邮件的第二个选项
    • 我刚试过,“For i = 0 ....”导致“对象不支持属性或方法”的错误。有什么想法吗?
    • 我今天早上测试了它,它对我有用,您的 oMapi 对象在代码执行期间是否设置正确?如果没有设置它会返回一个错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2021-12-29
    • 2021-11-28
    • 1970-01-01
    • 2021-01-31
    • 2014-03-15
    • 1970-01-01
    相关资源
    最近更新 更多