I am new to using VBA but I want to create a local personal folder in Outlook using the following script from https://learn.microsoft.com/en-us/office/vba/api/outlook.folder.folders.
I get error from the last line: Set myNewFolder = myFolder.Folders.Add("My Personal Contacts"): "Run-time error '-2147352567 (80020009)': Cannot create the folder. Any ideas would be appreciated.
Sub CreatePersonalContacts()
Dim myNamespace As Outlook.NameSpace
Dim myFolder As Outlook.Folder
Dim myNewFolder As Outlook.Folder
Set myNamespace = Application.GetNamespace("MAPI")
Set myFolder = myNamespace.GetDefaultFolder(olFolderContacts)
Set myNewFolder = myFolder.Folders.Add("My Personal Contacts")
End Sub
CodePudding user response:
Your code will successfully run only once. Once the subfolder is created, Folders.Add
will fail. Try to open the folder first and check if there was an error:
On Error Resume next
Set myNamespace = Application.GetNamespace("MAPI")
Set myFolder = myNamespace.GetDefaultFolder(olFolderContacts)
err.Clear
Set myNewFolder = myFolder.Folders.Item("My Personal Contacts")
If Err.Number <> 0 Then
Set myNewFolder = myFolder.Folders.Add("My Personal Contacts")
End If
CodePudding user response:
To be able to debug the code line-by-line and see how it is working under the hood you may paste it to the VBA editor (see ThisOutlookSession
module) and run it after setting a breakpoint.
I'd suggest checking whether such folder already exists in the Outlook profile. You can iterate over all subfolders by checking subfolder names, so your may be sure there is no such folder exists before you try to create a new one.
Another possible cause can be the place where and when your code is run. Microsoft does not currently recommend, and does not support, Automation of Microsoft Office applications from any unattended, non-interactive client application or component (including ASP, ASP.NET, DCOM, and NT Services), because Office may exhibit unstable behavior and/or deadlock when Office is run in this environment.
If you are building a solution that runs in a server-side context, you should try to use components that have been made safe for unattended execution. Or, you should try to find alternatives that allow at least part of the code to run client-side. If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
You may find a similar errors related to such scenarios, see System.Runtime.InteropServices.COMException (0x80020009): Cannot complete the operation. You are not connected.