[英]Excel VBA - Outlook Email into Excel
我已经进行了相当多的搜索,但我想出的一切都与我正在尝试做的相反。
我收到一大堆自动生成的电子邮件,我想把它们翻译成excel。 一切正常,除了它将它专门转储到一个单元格中。 我希望这可以让多行电子邮件作为 excel 中的多行出现。
例如,电子邮件正文是这样的。 这将有可变数量的行,所以我真的不能只使用 Mid 函数。
Hello,
Job AAA completed successfully.
ThingA1 = good
ThingA2 = error code 5
整个字符串显示在单元格 A2 下(这有点像我告诉它做的......但我不知道如何告诉它把它作为多个 ID)。 我希望它显示为不同的单元格(在本例中覆盖单元格 A2:A6)。
Sub ParseAllEmails()
'loop through the outlook inbox, find stuff with errors, parse/paste it in
Dim OutApp As Outlook.Application, OLF As Outlook.MAPIFolder, OutMail As Outlook.MailItem
Dim myReport As Boolean, zeroErrors As Boolean
Dim parseSht As Worksheet
Dim i As Long
'establish connection
Set OutApp = CreateObject("Outlook.Application")
Set OLF = OutApp.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set parseSht = ThisWorkbook.Sheets("parse")
'go through inbox looking for scheduler emails
For i = OLF.Items.Count To 1 Step -1
If TypeOf OLF.Items(i) Is MailItem Then
Set OutMail = OLF.Items(i)
myReport = (LCase(Left(OutMail.Subject, 3)) = "job")
zeroErrors = (InStr(1, LCase(OutMail.Subject), "errors=0") > 0)
If myReport And Not zeroErrors Then
parseSht.Range("A2:A500").Value = Trim(OutMail.Body)
Exit Sub
End If
End If
Next
End Sub
首先,我建议替换代码迭代收件箱文件夹中所有项目的以下部分:
'go through inbox looking for scheduler emails
For i = OLF.Items.Count To 1 Step -1
If TypeOf OLF.Items(i) Is MailItem Then
Set OutMail = OLF.Items(i)
myReport = (LCase(Left(OutMail.Subject, 3)) = "job")
zeroErrors = (InStr(1, LCase(OutMail.Subject), "errors=0") > 0)
If myReport And Not zeroErrors Then
使用Items
类的Find
/ FindNext
或Restrict
方法,这些方法只允许获取与您的条件相对应的项目。 您所需要的只是遍历结果集合并在之后处理这些项目。 在以下文章中阅读有关这些方法的更多信息:
要将单个消息正文字符串分成单独的行,您可以使用 VBA 中提供的 Slit 函数:
Dim strings() As String
strings = Split(mailItem.Body, vbNewLine)
因此,您可以通过将每个条目添加到单独的单元格(如果需要)来检测需要粘贴的数据并在循环中处理这些行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.