选择电子邮件正文,复制并使用VBA将其粘贴到Excel中

时间:2017-02-14 19:33:36

标签: vba excel-vba outlook-vba excel

我想选择特定电子邮件的正文,复制并粘贴到Outlook中。我知道在电子表格中按Ctrl + A然后按Ctrl + C会更容易,但这只是涉及报表自动化的更大过程的一部分。 这是我的代码:

Sub GetFromInbox()

Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFldr As Outlook.MAPIFolder
Dim olItms As Outlook.Items
Dim olMail As Variant
Dim i As Long

Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace(”MAPI”)
Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olItms = olFldr.Items

olItms.Sort “Subject”

i = 1

For Each olMail In olItms
    If InStr(olMail.Subject, “Criteria") > 0 Then
        ThisWorkbook.Sheets("YourSheet").Cells(i, 1).Value = outMail.Body
        i = i + 1
    End If
Next olMail

Set olFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing

End Sub

我在这一行收到语法错误:

If InStr(olMail.Subject, “Criteria") > 0 Then

所以我不知道我错过了什么或做错了所以请帮忙,因为我对VBA不是很有经验。

1 个答案:

答案 0 :(得分:1)

我会看两件事。首先,是您要将邮件正文粘贴到实际名为“YourSheet”的工作表,其次,您要引用outMail.Body,其中outMail从未被标注或设置。试试这个(假设要粘贴的工作表称为“Sheet1”)。

Sub GetFromInbox()

Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olFldr As Outlook.MAPIFolder
Dim olItms As Outlook.Items
Dim olMail As Variant
Dim i As Long

Set olApp = New Outlook.Application
Set olNs = olApp.GetNamespace("MAPI")
Set olFldr = olNs.GetDefaultFolder(olFolderInbox)
Set olItms = olFldr.Items

olItms.Sort "Subject"

i = 1

For Each olMail In olItms
    If InStr(1, olMail.Subject, "Criteria") > 0 Then
        ThisWorkbook.Sheets("Sheet1").Cells(i, 1).Value = olMail.Body
        i = i + 1
    End If
Next olMail

Set olFldr = Nothing
Set olNs = Nothing
Set olApp = Nothing

End Sub