【发布时间】:2020-06-21 07:04:18
【问题描述】:
我正在尝试根据接收日期下载 Outlook 收件箱中的电子邮件附件。我的代码下载附件,但它会跳过文件。
例如:我试图从最新的电子邮件(接收日期:01/14/2019)循环电子邮件。在循环了大约 10-15 封电子邮件后,它突然跳到阅读 2018 年 7 月 12 日收到的电子邮件。
Sub saveemailattachment()
'Application setup
Dim objOL As Outlook.Application
Set objOL = New Outlook.Application
Dim ONS As Outlook.Namespace
Set ONS = objOL.GetNamespace("MAPI")
Dim olfolder As Outlook.Folder
Set olfolder = ONS.GetDefaultFolder(olFolderInbox)
Dim olmail As Outlook.MailItem
Set olmail = objOL.CreateItem(olMailItem)
Dim olattachment As Outlook.Attachment
Dim i As Long
Dim filename As String
Dim VAR As Date
'Loop through all item in Inbox
For i = olfolder.Items.Count To 1 Step -1 'Iterates from the end backwards
Set olmail = olfolder.Items(i)
For Each olmail In olfolder
VAR = Format(olmail.ReceivedTime, "MM/DD/YYYY")
filename = olmail.Subject
If VAR = "1/14/2019" Then
For Each olattachment In olmail.Attachments
olattachment.SaveAsFile "C:\Users\Rui_Gaalh\Desktop\Email attachment\" & olattachment.filename
Next
Else
End If
'Mark email as read
olmail.UnRead = False
DoEvents
olmail.Save
Next
Next
MsgBox "DONE"
End Sub
【问题讨论】:
-
删除
For Each olmail In olfolder我不知道你为什么在那里。 -
我不明白这是如何找到今天收到的任何电子邮件的。对于 2019 年 1 月 14 日收到的电子邮件,
VAR = Format(olmail.ReceivedTime, "MM/DD/YYYY")会将VAR设置为 2019 年 1 月 14 日,不等于 2019 年 1 月 14 日。我会有类似的东西:Dim Midnight As DateMidnight = DateSerial(Year(Now()), Month(Now()), Day(Now()))这将Midnight设置为今天的时间 0:00:00。olmail.ReceivedTime >= Midnight将适用于今天的所有电子邮件。 -
如果您仍有问题,请告诉我