步骤1: 我要创建一个文件夹,如果它失败了(因为它可能已经存在),我希望它忽略并继续:
Sub MakeFolder()
'declare variables
Dim outlookApp As Outlook.Application
Dim NS As Outlook.NameSpace
'set up folder objects
Set outlookApp = New Outlook.Application
Set outlookApp = New Outlook.Application
Set NS = outlookApp.GetNamespace("MAPI")
Set objOwner = NS.CreateRecipient("email@host.com")
objOwner.Resolve
Set outlookInbox = NS.GetSharedDefaultFolder(objOwner, olFolderInbox)
'make a folder, maybe
Dim newFolder
On Error Resume Next
Set newFolder = outlookInbox.Folders.Add("myNewFolder")
On Error GoTo -1
On Error GoTo 0
End Sub
但我仍然收到错误消息:
我如何获得这种耐久?如果该文件夹不存在,它将顺利运行并创建它。
第二步: 我有一个文件夹列表(大约60个),该列表可能会随着时间而变化。因此,我想运行一个脚本来检查新文件夹,然后创建它们:
For Each fol In folders
On Error Resume Next
Set newFolder = outlookInbox.Folders.Add(fol)
If Err.Number <> 0 Then
On Error GoTo -1
Else:
Debug.Print fol & " created "
End If
On Error GoTo 0
Next ID
与此处相同,如果outlookInbox.Folders.Add()
无法创建该文件夹,则无论下一个返回值如何,都将引发错误。我该怎么办?
修改
[请参阅第一个评论以寻求解决方案]
答案 0 :(得分:0)
现在,您已经修复了IDE,可以使用以下代码
Option Explicit
Public Sub Example()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.Folder
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Dim SubFolder As Outlook.Folder
'// SubFolder Name
Dim FolderName As String
FolderName = "myNewFolder"
'// Check if folder exist else create one
If FolderExists(Inbox, FolderName) = True Then
Debug.Print "Folder Exists"
Set SubFolder = Inbox.Folders(FolderName)
Else
Set SubFolder = Inbox.Folders.Add(FolderName)
End If
End Sub
'// Function - Check folder Exist
Private Function FolderExists(Inbox As Folder, FolderName As String)
Dim Sub_Folder As MAPIFolder
On Error GoTo Exit_Err
Set Sub_Folder = Inbox.Folders(FolderName)
FolderExists = True
Exit Function
Exit_Err:
FolderExists = False
End Function