我不明白:If myFolder.Folders("Close") = 0 Then。 myFolder.Folders("Close") 是一个文件夹,我不会想到将它与零进行比较。您是否引用了解释此功能的站点,因为我想了解它?
如果文件夹不经常存在而无法编写函数,我希望创建一个文件夹。我的函数没有满足您要求的理想参数,但它可以工作。我将其作为经过测试的代码提供,可以满足您的需求,或者作为您自己代码的灵感来源。
子DemoGetCreateFldr展示了如何使用GetCreateFldr函数来达到我相信你寻求的效果。
我不使用GetDefaultFolder,因为在我的系统上,它返回对我不使用的商店的引用。 “Outlook 数据文件”是 Outlook 的默认存储,但向导为我的两个电子邮件地址中的每一个创建了一个单独的存储。在Set Store = Session.Folders("Outlook Data File") 中,将“Outlook 数据文件”替换为包含要为其创建子文件夹的收件箱的商店的名称。
GetCreateFldr 的第一次调用创建文件夹“Close”,如果它不存在,然后创建文件夹“EID1”。我保存对文件夹的引用,并使用 Debug.Print 来演示它返回正确的引用。
对于文件夹“EID2”和“EID3”,我不保存与您的代码匹配的参考。
如果文件夹“Close”、“EID1”、“EID2”和“EID3”存在,GetCreateFldr 不会尝试创建它们,尽管它仍会返回一个引用。
希望这会有所帮助。
Sub DemoGetCreateFldr()
Dim FldrEID1 As Folder
Dim FldrNameFull(1 To 3) As String
Dim Store As Folder
Set Store = Session.Folders("Outlook Data File")
FldrNameFull(1) = "Inbox"
FldrNameFull(2) = "Close"
FldrNameFull(3) = "EID1"
Set FldrEID1 = GetCreateFldr(Store, FldrNameFull)
Debug.Print FldrEID1.Parent.Parent.Parent.Name & "|" & _
FldrEID1.Parent.Parent.Name & "|" & _
FldrEID1.Parent.Name & "|" & _
FldrEID1.Name
FldrNameFull(3) = "EID2"
Call GetCreateFldr(Store, FldrNameFull)
FldrNameFull(3) = "EID3"
Call GetCreateFldr(Store, FldrNameFull)
End Sub
Public Function GetCreateFldr(ByRef Store As Folder, _
ByRef FldrNameFull() As String) As Folder
' * Store identifies the store, which must exist, in which the folder is
' wanted.
' * FldrNameFull identifies a folder which is or is wanted within Store.
' Find the folder if it exists otherwise create it. Either way, return
' a reference to it.
' * If LB is the lower bound of FldrNameFull:
' * FldrNameFull(LB) is the name of a folder that is wanted within Store.
' * FldrNameFull(LB+1) is the name of a folder that is wanted within
' FldrNameFull(LB).
' * FldrNameFull(LB+2) is the name of a folder that is wanted within
' FldrNameFull(LB+1).
' * And so on until the full name of the wanted folder is specified.
' 17Oct16 Date coded not recorded but must be before this date
Dim FldrChld As Folder
Dim FldrCrnt As Folder
Dim ChildExists As Boolean
Dim InxC As Long
Dim InxFN As Long
Set FldrCrnt = Store
For InxFN = LBound(FldrNameFull) To UBound(FldrNameFull)
ChildExists = True
' Is FldrNameFull(InxFN) a child of FldrCrnt?
On Error Resume Next
Set FldrChld = Nothing ' Ensure value is Nothing if following statement fails
Set FldrChld = FldrCrnt.Folders(FldrNameFull(InxFN))
On Error GoTo 0
If FldrChld Is Nothing Then
' Child does not exist
ChildExists = False
Exit For
End If
Set FldrCrnt = FldrChld
Next
If ChildExists Then
' Folder already exists
Else
' Folder does not exist. Create it and any children
Set FldrCrnt = FldrCrnt.Folders.Add(FldrNameFull(InxFN))
For InxFN = InxFN + 1 To UBound(FldrNameFull)
Set FldrCrnt = FldrCrnt.Folders.Add(FldrNameFull(InxFN))
Next
End If
Set GetCreateFldr = FldrCrnt
End Function