【问题标题】:Copy the body of an email into Excel using VBA使用 VBA 将电子邮件正文复制到 Excel
【发布时间】:2017-02-14 19:33:36
【问题描述】:

我想选择特定电子邮件的正文,将其复制并粘贴到 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

【问题讨论】:

  • InStr 的第一个参数是起始位置。试试If InStr(1, olMail.Subject, “Criteria") > 0 Then
  • @TonyDallimore 谢谢!错过了那部分!...我在下一行收到一个错误,说运行时错误 424 需要对象?抱歉,我在 VBA 中编码才 3 个月!
  • 将 Option Explicit 放在模块的顶部。在工具 |选项 |编辑器选项卡 - “需要变量声明”。
  • 你有For Each olMail In olItmsoutMail.BodyolMailoutMail 必须相同。我同意尼丁; Option Explicit 将帮助您在运行代码之前检测这些错误。
  • 修正你的 " " 引号,它们看起来不同

标签: excel vba outlook


【解决方案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

【讨论】:

  • 感谢这位伙伴!它现在可以工作,但所有电子邮件都被复制到 1 个单元格上,而不是 HTML 格式。如果您有任何建议,欢迎他们,但我也会尝试找到答案。
  • @RaulGonzales 如果您对 HTML 感兴趣,请将 olMail.Body 替换为 olMail.HTMLBody - 请记住,这将提供标记,但会显示为文本。就它在一个单元格中的粘贴而言,您在循环中保持了 i=i+1,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 2017-03-02
  • 1970-01-01
相关资源
最近更新 更多