【发布时间】:2020-06-27 15:38:50
【问题描述】:
我有一个 VBA 脚本,可以将传入的 Outlook 电子邮件提取到 txt 文件中。代码如下:
' General Declarations
Option Explicit
' Public declarations
Public Enum olSaveAsTypeEnum
olSaveAsTxt = 0
olSaveAsRTF = 1
olSaveAsMsg = 3
End Enum
Sub Export_MailasMSG(item As Outlook.MailItem)
' Routine will take all selected mails and export them as .MSG files to the
' directory defined by
' Error Handling
On Error Resume Next
' Varaiable Declarations
Dim strExportFolder As String: strExportFolder = "C:\OutlookEmails\"
Dim strExportFileName As String
Dim strExportPath As String
Dim strReceivedTime As String
Dim strSubject As String
Dim objRegex As Object
' Initiate regex search
Set objRegex = CreateObject("VBScript.RegExp")
With objRegex
.Pattern = "(\s|\\|/|<|>|\|\|\?|:)"
.Global = True
.IgnoreCase = True
End With
' If the currently selected item is a mail item we can proceed
If TypeOf item Is Outlook.MailItem Then
' Format the file name
strReceivedTime = item.ReceivedTime
strSubject = item.Subject
strExportFileName = Format(strReceivedTime, "yyyymmdd", vbUseSystemDayOfWeek, _
vbUseSystem) & Format(strReceivedTime, "-hhnnss", _
vbUseSystemDayOfWeek, vbUseSystem) & "-" & strSubject
strExportFileName = objRegex.Replace(strExportFileName, "_")
' Export to the predefined folder.
strExportPath = strExportFolder & strExportFileName & ".txt"
item.SaveAs strExportPath, olSaveAsTxt
' MsgBox ("Email saved to: " & strExportPath)
Else
' This is not an email item.
End If
' Clear routine memory
Set item = Nothing
Set objRegex = Nothing
End Sub
我得到的txt文件如下:
From: Name Surname <email@address.com
Sent: mercoledì 17 gennaio 2018 12:16
To: email@email.com
Subject: subject here
BODY HERE
我可以只提取邮件正文而不提取发件人、发送人、收件人和主题行吗? 如果是这样,我该如何实现?我不懂 VBA 编程。
我尝试将这一行 "item.SaveAs strExportPath, olSaveAsTxt" 更改为 " item.Body.SaveAs strExportPath, olSaveAsTxt",但没有成功。
【问题讨论】:
-
在您的代码中,
item是整个 MailItem。如果您保存item,您将获得一切。您以item.xxxx访问MailItem 的一部分。例如,您访问item.ReceivedTime。您想为文本正文保存item.Body或为 Html 正文保存item.HtmlBody。item.Body和item.HtmlBody是字符串,所以保存为文本文件。 -
如果你像这样使用
On Error Resume Next,你的意思是:“不要费心告诉我任何问题,因为我喜欢晦涩难懂的失败。”要正确使用它,请写On Error Resume NextSingle statement that might failOn Error GoTo 0Check Err... 。使用您的方法,任何语句都可能失败,并且代码执行将像以前那样继续执行。使用推荐的方法,您可以为选定的语句提供定制的错误处理。 -
在前面的评论中,倒数第二句话应该是:“使用你的方法,任何语句都可能失败,代码执行将继续虽然它已经工作了。”