I want to move an email from a shared inbox to a shared subfolder in the same inbox.
I have two mailboxes and the shared one is the second.
"Outbound TTA" = the name of the second shared mailbox.
"réception" = the name of the Inbox folder in the "Outbound TTA"
"MyFolderEmails" = the name of the subfolder in the "réception" folder.
The code works only once!
The second time it shows
Run-time error '-2147221233 (8004010f)':The attempted operation failed. An object could not be found.
The error appears at Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
Public Sub test2()
MoveSelectionToFolder
End Sub
Private Sub MoveSelectionToFolder()
Dim NS As nameSpace
Dim sharedInbox As folder
Dim sharedDestinationFolder As folder
Dim sharedItems As Selection
Dim i As Long
Set NS = Application.GetNamespace("MAPI")
Set sharedInbox = NS.Folders("Outbound TTA").Folders("réception")
Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
Set sharedItems = ActiveExplorer.Selection
For i = sharedItems.Count To 1 Step -1
sharedItems(i).Move sharedDestinationFolder
Next i
Set NS = Nothing
Set sharedItems = Nothing
Set sharedInbox = Nothing
Set sharedDestinationFolder = Nothing
End Sub
Also, even similar codes have the same fate, work only once; after that they show the error.
Ok try to preserve the reference to the folder as a static variable like this. (restart your outlook and then use the code)
' Set it as a static variable
Global sharedDestinationFolder As Folder
Public Sub test2()
MoveSelectionToFolder
End Sub
Private Sub MoveSelectionToFolder()
Dim NS As Namespace
Dim sharedInbox As Folder
'Dim sharedDestinationFolder As Folder
Dim sharedItems As Selection
Dim i As Long
If sharedDestinationFolder Is Nothing Then
Set NS = Application.GetNamespace("MAPI")
Set sharedInbox = NS.Folders("Outbound TTA").Folders("réception")
Set sharedDestinationFolder = sharedInbox.Folders("MyFolderEmails")
MsgBox "Setting destination folder"
End If
Set sharedItems = ActiveExplorer.Selection
For i = sharedItems.Count To 1 Step -1
If TypeName(sharedItems(i)) = "MailItem" Then
sharedItems(i).Move sharedDestinationFolder
End If
Next i
Set NS = Nothing
Set sharedItems = Nothing
Set sharedInbox = Nothing
'Set sharedDestinationFolder = Nothing
End Sub
In theory, the first time you run the code you will see the message box. When you run it again, it won't be Nothing
and therefore, it should have a valid reference to the correct folder (again in theory)