I'm trying to move an email in my Outlook 2010 inbox to a sub-folder of a folder (called "Indidents").
The move is being performed by a VBA routine which is passed a sub-folder name (a problem incident reference) and a reference to the email.
If the sub-folder does not exists, it is to be created.
The move works if I have to create the folder, but if the sub-folder already exists then the move fails.
Here is my code:
Sub AddIncidentFolder(incident, ByRef email As Outlook.mailItem)
incidentDir = "Incidents"
Dim myNameSpace As Outlook.NameSpace
Dim inbox As Outlook.Folder
' Dim incidents As Outlook.Folder
Dim incidentSubFolder As Outlook.Folder
Set myNameSpace = Application.GetNamespace("MAPI")
Set inbox = myNameSpace.GetDefaultFolder(olFolderInbox)
MsgBox "Selecting " & incidentDir & " folder"
Set incidents = inbox.Folders.item(incidentDir)
MsgBox "Selecting " & incident & " sub-folder"
On Error GoTo addSubFailed
Set incidentSubFolder = incidents.Folders.Add(incident)
MsgBox "Incident sub-folder set to " & incidentSubFolder
On Error GoTo MoveError
email.Move incidentSubFolder
Exit Sub
addSubFailed:
MsgBox "Error Creating 'Incident' folder " & incident
MsgBox "Error number: " & Err.Number _
& " " & Err.Description
Set incidentSubFolder = incidents.Folders.item(incident)
MsgBox "folder add result was " & incidentSubFolder
Resume Next
MoveError:
MsgBox "Move of email failed"
Resume Next
End Sub
So the idea is that if the 'Add Folder' fails then I assume it exists so I just select the folder in addSubFailed
.
The first 2 MsgBox statements in addSubFailed
fire, but the third one doesn't, so I assume that the 'Set' for the sub-folder is causing a further error.
I'm pretty new to VBA but OK with objects, properties etc. The code came from other SO answers and MS docs and I can't see anything obviously wrong.
EDIT The 'incident' variable which I thought was a string is actually a Regex match object, from this calling code:
For Each Match In irMatches
'MsgBox "Match is " & Match & ", value is " & Match.Value
Call addToCategory(Match, email)
Call AddIncidentFolder(Match, email)
Next
If I change the addSubFailed
routine to:
addSubFailed:
MsgBox "Error Creating 'Incident' folder " & incident
MsgBox "Error number: " & Err.Number _
& " " & Err.Description
MsgBox "Incident is " & incident
'Set incidentSubFolder = incidents.Folders(incident)
Set incidentSubFolder = incidents.Folders("INC000001509771")
MsgBox "folder is " & incidentSubFolder
Resume Next
then it works, so I have a type-mismatch I think. Adding `As String' to the 'incident' parm gives me a type mis-match run-time error.
Thanks in advance for any help.