简体   繁体   English

VBA 如何从最近一封开始循环浏览 outlook 中的电子邮件

[英]VBA how to loop through emails in outlook starting on the most recent one

I'd like to create a program that loops through all the emails on my inbox but stops as soon as it gets a hit (to make the program lighter).我想创建一个程序,循环遍历我收件箱中的所有电子邮件,但一旦被点击就停止(使程序更轻)。 This one already works but the hit I get is the oldest one.这个已经起作用了,但我得到的是最老的一个。 I'd like to start my loop on the most recent one.我想从最近的循环开始。 Here's the code这是代码

Dim objNS As Outlook.Namespace: Set objNS = GetNamespace("MAPI")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
Dim Item As Object

For Each Item In olFolder.Items
    If TypeOf Item Is Outlook.MailItem Then
        Dim oMail As Outlook.MailItem: Set oMail = Item
        If InStr(oMail.Subject, "Whatever") > 0 Then
            'Do something
            Exit For
        End If
    End If
Next

You can use the Items.Sort method of the MAPIFolder object.您可以使用MAPIFolder object 的Items.Sort方法。

Dim objNS As Outlook.Namespace: Set objNS = GetNamespace("MAPI")
Dim olFolder As Outlook.MAPIFolder
Set olFolder = objNS.GetDefaultFolder(olFolderInbox)
olFolder.Items.Sort "ReceivedTime", True  ' Sort items by received date in descending order
Dim Item As Object

For Each Item In olFolder.Items
    If TypeOf Item Is Outlook.MailItem Then
        Dim oMail As Outlook.MailItem: Set oMail = Item
        If InStr(oMail.Subject, "Whatever") > 0 Then
            'Do something
            oMail.ReplyAll 
            oMail.Display 'This will open the reply window
            Exit For
        End If
    End If
Next

Never loop through all items in a folder, always use Items.Find/FindNext (if you want to find one or more items) or Items.Restrict (if you want to find all matches).切勿遍历文件夹中的所有项目,始终使用Items.Find/FindNext (如果要查找一个或多个项目)或Items.Restrict (如果要查找所有匹配项)。

If you want the items in a particular order, sort them first using Items.Sort , eg, Items.Sort "ReceivedTime", true如果您想要特定顺序的项目,请先使用Items.Sort对它们进行排序,例如Items.Sort "ReceivedTime", true

In you participial case, use a query like the one below.在您参与的情况下,使用如下所示的查询。 Note that it is on the PR_NORMALIZED_SUBJECT MAPI property since it is indexed (unlike PR_SUBJECT ).请注意,它位于PR_NORMALIZED_SUBJECT MAPI 属性上,因为它已编入索引(与PR_SUBJECT不同)。

@SQL="http://schemas.microsoft.com/mapi/proptag/0x0E1D001F" LIKE '%whatever%'

The following will do the job:以下将完成这项工作:

set oItems = olFolder.Items
oItems.Sort "ReceivedTime", true
set oMail = oItems.Find "@SQL=""http://schemas.microsoft.com/mapi/proptag/0x0E1D001F"" LIKE '%whatever%'"
if not (oMail is Nothing) Then
  'Do something
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM