sparkforce
sparkforce

Reputation: 1

How do I move an email in Outlook to a subfolder?

I am trying to create a macro that will move items in my Outlook inbox to a subfolder of another folder that is on the same level as the Inbox (i.e., the parent folder is not a sub-folder of the inbox). This is the code I am using:

Sub EventRequests()
On Error Resume Next

Dim ns As Outlook.NameSpace
Dim moveToFolder As Outlook.MAPIFolder
Dim objItem As Outlook.MailItem

Set ns = Application.GetNamespace("MAPI")

'Define path to the target folder
Set moveToFolder = ns.Folders("Events").Folders("Event Requests")

If Application.ActiveExplorer.Selection.Count = 0 Then
   MsgBox ("Select an E-mail first")
   Exit Sub
End If

If moveToFolder Is Nothing Then
   MsgBox "Target folder not found!", vbOKOnly + vbExclamation, "Move Macro Error"
End If

For Each objItem In Application.ActiveExplorer.Selection
   If moveToFolder.DefaultItemType = olMailItem Then
      If objItem.Class = olMail Then
         objItem.Move moveToFolder
      End If
  End If
Next

Set objItem = Nothing
Set moveToFolder = Nothing
Set ns = Nothing
End Sub

When I run the code I get an error that says "Target folder not found!" I tried Set moveToFolder = ns.GetDefaultFolder(olFolderInbox).Folders("Events").Folders("Event Requests")and Set MoveToFolder = ns.Folders("Mailbox - my name").Folders(targetFolder) but neither of those worked. I have a different macro set up that moves messages in my inbox to a folder that is a subfolder of my inbox and it works fine:

Set moveToFolder = ns.GetDefaultFolder(olFolderInbox).Folders("Completed")

How do I fix the target path so that it points to the correct subfolder?

Upvotes: 0

Views: 341

Answers (1)

sparkforce
sparkforce

Reputation: 1

I'm going to go ahead and post an answer to my own question so that if other people in the future have this issue they can see the code I arrived at that works:

Sub EventRequests()

Dim ns As Outlook.NameSpace
Dim moveToFolder As Outlook.MAPIFolder
Dim objItem As Outlook.MailItem

Set ns = Application.GetNamespace("MAPI")

On Error GoTo 0
Set moveToFolder = ns.GetDefaultFolder(olFolderInbox).Parent.Folders("Events").Folders("Event Requests")


If Application.ActiveExplorer.Selection.Count = 0 Then
   MsgBox ("Select an E-mail first")
   Exit Sub
End If

If moveToFolder Is Nothing Then
   MsgBox "Target folder not found!", vbOKOnly + vbExclamation, "Move Macro Error"
End If

For Each objItem In Application.ActiveExplorer.Selection
   If moveToFolder.DefaultItemType = olMailItem Then
      If objItem.Class = olMail Then
         objItem.Move moveToFolder
      End If
  End If
Next

Set objItem = Nothing
Set moveToFolder = Nothing
Set ns = Nothing
End Sub

Upvotes: 0

Related Questions