【发布时间】:2020-10-18 06:33:25
【问题描述】:
在 Excel VBA 中遍历 Outlook.Folders 的最有效方法是什么?我对 Excel VBA 有点陌生,目前正在使用递归遍历文件夹。
以下代码有效,但有什么比我编写的代码更好的吗?
Private Function RecursiveEmailItems( _
Optional SubjectContains As String = Empty, _
Optional FolderType As OlDefaultFolders = olFolderInbox, _
Optional StartFolderNm As String = "", _
Optional Folder As Outlook.Folder = Nothing, _
Optional FolderDepth As Long = 1)
Dim Filter As String ' Stores outlook filter
Dim Emails As Outlook.Items ' Stores list of outlook emails
Dim Email As Outlook.MailItem ' Stores an email item
Dim oTest As Object ' Used to test email/folder item
If SubjectContains <> "" Then Filter = "@SQL=urn:schemas:httpmail:subject ci_phrasematch '" _
& SubjectContains & "'"
'-- Check to see if need to initialize folder - First Run --
If Folder Is Nothing Then
If StartFolderNm = "" Then Set Folder = _
Outlook.Application.GetNamespace("MAPI").GetDefaultFolder(FolderType) _
Else Set Folder = _
Outlook.Application.GetNamespace("MAPI").GetDefaultFolder(FolderType).Folders(StartFolderNm)
End If
'-- Get emails from the folder, use filter if not empty
If Filter = "" Then Set Emails = Folder.Items Else Set Emails = Folder.Items.Restrict(Filter)
'-- Process all emails found --
If Emails.Count > 0 Then Debug.Print Indent(FolderDepth, " ") & "-" & Folder.Name
For Each oTest In Emails
If TypeName(oTest) = "MailItem" Then
Set Email = oTest
Debug.Print Indent(FolderDepth, " ") & " |" & Email.Subject
End If
Next oTest
'-- Process all subfolders --
For Each oTest In Folder.Folders
If TypeName(oTest) = "MAPIFolder" Then
Call RecursiveEmailItems(SubjectContains, FolderType, StartFolderNm, oTest, FolderDepth + 1)
End If
Next oTest
End Function
Private Function GetEmailStatus()
'Dim Filter As String: Initialize: Filter = "Timesheet " & Format(EndDt, "mm/dd/yy")
Dim Filter As String: Initialize: Filter = "Timesheet 06"
Call RecursiveEmailItems("Timesheet 06/", olFolderInbox, "Timesheet")
End Function
Private Function Indent(Count As Long, Char As String) As String
Dim idx As Long
For idx = 1 To Count
Indent = Indent + Char
Next
End Function
提前感谢您的帮助!
【问题讨论】:
-
除非你有成千上万个文件夹,否则你做什么都没有区别。您可以使用循环 if 您知道您的文件夹深度。如果你不使用递归。所以这取决于你对数据有什么特殊的了解。
标签: excel vba recursion outlook directory