For Each 循环不删除所有项目 [英] For Each loop not deleting all items
问题描述
我有一个宏,它应该在我退出 Outlook 2007 时删除超过 'x' 天的电子邮件,但它似乎只删除了其中的一些,当我打开它并再次退出时,它删除了其余的.代码如下:
I have a macro which is supposed to delete emails over 'x' amount of days old when I quit Outlook 2007 but it only seems to delete a few of them and when I open it and quit again it deleted the rest. Here is the code:
Private Sub Application_Quit()
Dim myOlApp, myNameSpace As Object
Dim MyItem As Object
Dim DeletedFolder As Object
Set myOlApp = CreateObject("Outlook.Application")
Set myNameSpace = myOlApp.GetNamespace("MAPI")
'Set DeletedFolder = myNameSpace.GetDefaultFolder(olFolderDeletedItems)
Set DeletedFolder = myNameSpace.GetDefaultFolder(olFolderInbox).Folders("Auto")
For Each MyItem In DeletedFolder.Items
If DateDiff("d", MyItem.ReceivedTime, Now) > 7 Then
MyItem.Delete
End If
Next
End Sub
在本例中,我在收件箱文件夹下的自动文件夹中选择了 7 天以上.知道为什么第一次不删除它们吗?
In this example I chose greater than 7 days old in the Auto folder under my Inbox folder. Any ideas why it does not delete them all the first time?
谢谢
推荐答案
通常在删除时需要不同类型的迭代:
Generally when deleting you need a different sort of iteration:
Dim m as Long
For m = DeletedFolder.Items.Count to 1 Step -1
Set myItem = DeletedFolder.Items(m)
If DateDiff("d", MyItem.ReceivedTime, Now) > 7 Then
MyItem.Delete
End If
Next
这是因为,当您从集合中删除一个元素时,该集合会重新建立索引.所以你需要在集合中向后退一步,否则你会跳过"一些项目.
This is because, as you delete an element from the collection, the collection is re-indexed. So you need to step backwards through the collection, otherwise you will "skip" some items.
这篇关于For Each 循环不删除所有项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!