我的Outlook VBA确实可以实现我想要的功能。它将先前工作日的电子邮件移动到新文件夹,并在辅助电子邮件收件箱中执行此操作。
我正在寻找有关如何使其更快地移动电子邮件的建议。
如果我手动将所有电子邮件复制到另一个文件夹,则将花费几秒钟。当我运行代码时,它需要几分钟。这是我的代码:
Option Explicit
Sub Move_Yesterdays_Emails()
'***Creates a new folder named yesterdays date under the inbox***
Dim myNameSpace As Outlook.NameSpace
Dim strMailboxName As String
Dim myFolder As Outlook.Folder
Dim myNewFolder As Outlook.Folder
Dim xDay As String
Dim XDate As Date
Dim thatDay As String
strMailboxName = "Deductions Backup"
If Weekday(Now()) = vbMonday Then
XDate = Date - 3
Else
XDate = Date - 1
End If
thatDay = WeekdayName(Weekday(XDate))
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = Session.Folders(strMailboxName)
Set myFolder = myFolder.Folders("Inbox")
Set myNewFolder = myFolder.Folders.Add(XDate & " " & thatDay)
'***Finds all emails in the inbox from yesterday and moves them to the created folder***
Dim Inbox As Outlook.MAPIFolder
Dim Items As Outlook.Items
Dim Item As Object
Dim Filter As String
Dim i As Long
Filter = "[ReceivedTime] >= '" & _
CStr(XDate) & _
" 12:00AM' AND [ReceivedTime] < '" & _
CStr(XDate + 1) & " 12:00AM'"
Debug.Print Filter
Set myNameSpace = Application.GetNamespace("MAPI")
Set myFolder = Session.Folders(strMailboxName)
Set Inbox = myFolder.Folders("Inbox")
Set Items = Inbox.Items.Restrict(Filter)
Items.Sort "[ReceivedTime]"
For i = Items.Count To 1 Step -1
DoEvents
If TypeOf Items(i) Is MailItem Then
Debug.Print Items(i)
Set Item = Items(i)
Item.Move myNewFolder
End If
Next
End Sub
有人知道为什么它比手动移动项目要慢得多,或者如何使它运行得更快?我不明白为什么比手工完成需要更长的时间。
答案 0 :(得分:1)
与其在查看和移动它们之前过滤邮件,不如尝试简单地查看它们,然后决定是否移动它们。
例如,一个简单的for Loop可以达到目的:
For Each item In Inbox.Items
If TypeOf item Is MailItem Then
If item.ReceivedTime < Date And item.ReceivedTime > Date - 1 Then
item.Move myNewFolder
End If
End If
Next
过滤某些东西非常慢。
但是请注意,我不是100%肯定Date - 1
适用于午夜后不久收到的邮件。