如果有该文件夹通过,否则创建它

时间:2019-07-11 17:04:18

标签: vba outlook outlook-vba

如果Outlook中有一个文件夹,而不仅仅是传递并运行其余的代码,我想创建一个代码,而不是仅运行其余的代码,则创建该文件夹

    Sub MoveItems()

 Dim myNameSpace As Outlook.NameSpace
 Dim myInbox As Outlook.Folder
 Dim myDestFolder As Outlook.Folder
 Dim myitems As Outlook.Items
 Dim myitem As Object
 Dim objApp As Outlook.Application
 Dim objFolder As Outlook.Folder
 Dim objTestFolder As Outlook.Folder

    Set objFolder = objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

    On Error Resume Next
    Set objTestFolder = objFolder.Folders("test")
    If objTestFolder Is Nothing Then
        Set objTestFolder = objFolder.Folders.Add("test", Outlook.OlDefaultFolders.olFolderInbox)
    End If
    On Error GoTo 0

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
 Set myitems = myInbox.Items
 Set myDestFolder = myInbox.Folders("test")

 Set oDeletedItems = Application.Session.GetDefaultFolder(olFolderDeletedItems)
 Set myitems = oDeletedItems.Items

 Debug.Print myitems.Count

 For I = myitems.Count To 1 Step -1
    myitems.Item(I).Move myDestFolder

 Next

End Sub

3 个答案:

答案 0 :(得分:0)

https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/object-required-error-424

您没有使用Set来分配objFolder

在VBA中,将对象分配给变量时,Set是必需的。

请参阅:What does the keyword Set actually do in VBA?

答案 1 :(得分:0)

通常,您应使用以下结构:

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

因此,请改用以下代码:

Sub MoveItems()

 Dim myNameSpace As Outlook.NameSpace
 Dim myInbox As Outlook.Folder
 Dim myDestFolder As Outlook.Folder
 Dim myitems As Outlook.Items
 Dim myitem As Object
 Dim objApp As Outlook.Application
 Dim objFolder As Outlook.Folder
 Dim objTestFolder As Outlook.Folder

 Set myNameSpace = Application.GetNamespace("MAPI")
 Set myInbox = myNameSpace.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

    On Error Resume Next
    Set objTestFolder = myInbox.Folders("test")
    If objTestFolder Is Nothing Then
        Set myDestFolder = myInbox.Folders.Add("test", Outlook.OlDefaultFolders.olFolderInbox)
    End If
    On Error GoTo 0

 Set oDeletedItems = Application.Session.GetDefaultFolder(olFolderDeletedItems)
 Set myitems = oDeletedItems.Items

 Debug.Print myitems.Count

 For I = myitems.Count To 1 Step -1
    myitems.Item(I).Move myDestFolder

 Next

End Sub

答案 2 :(得分:0)

如上所述,您需要使用关键字Set将对象分配给变量。以下代码将首先检查该文件夹是否已经存在。如果没有,它将创建一个。

Dim objFolder As Outlook.Folder
Dim objTestFolder As Outlook.Folder

Set objFolder = objNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderInbox)

On Error Resume Next
Set objTestFolder = objFolder.Folders("test")
If objTestFolder Is Nothing Then
    Set objTestFolder = objFolder.Folders.Add("test", Outlook.OlDefaultFolders.olFolderInbox)
End If
On Error GoTo 0