我想递归地遍历我所有的outlook文件夹,将它们添加到一个数组中,并返回一个函数,这样我就可以从多个地方调用它。
我需要添加的对象类型是Outlook.Folder
,所以我从Dim output() As Outlook.Folder
开始,这为我提供了一系列错误#91。
我发现我可以声明数组Dim output() As Variant
按以下顺序工作:
Dim SubFolderCount As Integer
SubFolderCount = Folder.Folders.Count
Dim output() As Variant
ReDim output(SubFolderCount)
Dim c As Integer
c = -1
'Debug.Print Folder.Name
'GetSubfolders = Folder.Folders.Count
For Each SubFolder In Folder.Folders
c = c + 1
output(c) = SubFolder
'GetSubfolders = GetSubfolders + GetSubfolders(SubFolder)
Next SubFolder
GetSubfolders = output
我发现我添加到这个Variant
数组的任何东西都变成了Variant/String
类型。
只是为了确定,我从函数返回了该数组,循环遍历结果并确保我不能将数组内容用作Outlook.Folder
类型,我只能将其用作String
。
是否可能,只有原语可以被分配到数组中?
我很确定我看到过他们添加工作表的例子。
您错过了"set";
set output(c) = SubFolder
话虽如此,我宁愿存储文件夹条目id(字符串),并使用Namespace.GetFolderFromID
按需打开文件夹。一旦文件夹被处理,您可以通过将其设置为Nothing
来释放它。
此代码使用字典存储本地文件夹名称和路径
Sub RecurseFolderStructure()
' Requires Reference: Microsoft Scripting Runtime
Dim ThisNamespace As Outlook.NameSpace: Set ThisNamespace = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder: Set Inbox = ThisNamespace.GetDefaultFolder(olFolderInbox)
'Dim Cal As Outlook.MAPIFolder: Set Cal = ThisNamespace.GetDefaultFolder(olFolderCalendar)
Dim Junk As Outlook.MAPIFolder: Set Junk = ThisNamespace.GetDefaultFolder(olFolderJunk)
Dim BaseFolder As Outlook.MAPIFolder: Set BaseFolder = Inbox '.Folders("SubFolder1SubFolder2...")
Dim Folders As Scripting.Dictionary: Set Folders = New Scripting.Dictionary
AddSubFolders BaseFolder, Folders
Dim f As Outlook.MAPIFolder
Dim Key As Variant
For Each Key In Folders
'Further Code; for eg.
Set f = Folders(Key)
Debug.Print f.FolderPath
Next Key
Folders.RemoveAll
Set Folders = Nothing
End Sub
Function AddSubFolders(ByRef CurrentFolder As Outlook.MAPIFolder, ByRef dict As Scripting.Dictionary)
Dim Folder As Outlook.MAPIFolder
If Not dict.Exists(CurrentFolder.FolderPath) Then dict.Add CurrentFolder.FolderPath, CurrentFolder
If CurrentFolder.Folders.Count > 0 Then
For Each Folder In CurrentFolder.Folders
AddSubFolders Folder, dict
Next
End If
End Function