You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Visual Basic for Applications方法查找指定Outlook邮件

使用VBA按主题检索Outlook邮件的实现方法

首先需提前在VBA编辑器中完成Outlook对象库引用:点击「工具」-「引用」,勾选对应版本的Microsoft Outlook xx.x Object Library即可。

常用检索方法

1. Items.Restrict方法(推荐,适合大数量邮件场景)

该方法可以直接按筛选条件过滤出符合要求的所有邮件集合,无需逐一遍历所有邮件,检索效率更高。
示例代码:

Sub SearchOutlookMailBySubject()
    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.Namespace
    Dim olFolder As Outlook.MAPIFolder
    Dim filterStr As String
    Dim targetMails As Outlook.Items
    Dim mail As Outlook.MailItem
    
    ' 初始化Outlook对象
    Set olApp = New Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")
    ' 这里指定检索的文件夹,olFolderInbox代表收件箱,可按需修改为其他文件夹
    Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox)
    
    ' 定义主题筛选规则,下面示例是模糊匹配包含"测试主题"的邮件,不区分大小写
    ' 若需要精确匹配,把@SQL=后面的内容改为urn:schemas:httpmail:subject = '你的精确主题'即可
    filterStr = "@SQL=urn:schemas:httpmail:subject LIKE '%测试主题%'"
    
    ' 应用筛选得到目标邮件集合
    Set targetMails = olFolder.Items.Restrict(filterStr)
    
    ' 遍历匹配到的邮件,可按需获取对应属性
    For Each mail In targetMails
        Debug.Print "邮件主题:" & mail.Subject
        Debug.Print "发件人:" & mail.SenderName
        Debug.Print "纯文本正文:" & mail.Body
        Debug.Print "HTML格式正文:" & mail.HTMLBody
        Debug.Print "接收时间:" & mail.ReceivedTime
        Debug.Print "-------------------------"
    Next
    
    ' 释放对象
    Set mail = Nothing
    Set targetMails = Nothing
    Set olFolder = Nothing
    Set olNamespace = Nothing
    Set olApp = Nothing
End Sub

2. Items.Find/FindNext方法(适合逐次匹配场景)

该方法适合逐个获取匹配邮件的场景,符合条件后可以直接终止检索,不需要遍历全部匹配结果。
示例代码:

Sub SearchMailWithFind()
    Dim olApp As Outlook.Application
    Dim olNamespace As Outlook.Namespace
    Dim olFolder As Outlook.MAPIFolder
    Dim filterStr As String
    Dim mail As Object
    
    Set olApp = New Outlook.Application
    Set olNamespace = olApp.GetNamespace("MAPI")
    Set olFolder = olNamespace.GetDefaultFolder(olFolderInbox)
    
    ' 筛选规则和Restrict方法通用
    filterStr = "@SQL=urn:schemas:httpmail:subject LIKE '%测试主题%'"
    
    ' 开始查找
    Set mail = olFolder.Items.Find(filterStr)
    Do While Not mail Is Nothing
        If TypeName(mail) = "MailItem" Then
            ' 此处按需获取邮件属性
            Debug.Print mail.Subject, mail.ReceivedTime
        End If
        ' 查找下一个匹配项
        Set mail = olFolder.Items.FindNext
    Loop
    
    Set mail = Nothing
    Set olFolder = Nothing
    Set olNamespace = Nothing
    Set olApp = Nothing
End Sub

注意事项

  • 筛选条件中%是通配符,代表任意数量的任意字符,去掉通配符即可实现精确匹配
  • 若需要检索其他文件夹,可修改GetDefaultFolder的参数,或者通过文件夹路径遍历指定自定义文件夹
  • 邮件正文分为纯文本格式的Body属性、HTML格式的HTMLBody属性,可按需取用
  • 检索共享邮箱邮件时,需将GetDefaultFolder替换为GetSharedDefaultFolder指定共享邮箱账号

内容的提问来源于stack exchange,提问作者Julius Hamilton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:06:11