PDA

View Full Version : Move emails to specified folder after assigning certain category



C0NN3CT3D
05-22-2018, 05:12 AM
Hello im new on VBA, and I would like to have a code that would automatically move emails to match folders or subfolders already created once I assigned a category, and be removed from it as soon as I removed the category, for example:
I have the folders organized this way:



1.Inbox

--1.2. What
------1.2.1. Invoice
------1.2.3. Budget

--1.3. When
------1.3.1 October
------1.3.2 September

--1.4. Where
------1.4.1. Lisbon

--1.5. Who
------1.5.1. John

------1.5.2. Stewart
------1.5.3. William


If I assigned the category "John" and "Budget", the message is moved to folder 1.2.3. Budgets and 1.5.1. John, and if i set no category the message will return to inbox.

Is this possible?!

Cheers

skatonni
05-25-2018, 02:00 PM
Appears to be feasible.

To start, you could try with a variant of this http://www.vbaexpress.com/forum/showthread.php?62611-Category-to-Folder .


Sub CopyMoveByCategory()

Dim olItems As Items
Dim olItem As Object

Dim i As Long

Dim copyMail As mailItem
Dim copyFlag As Boolean

Dim inboxFolder As Folder
Dim targetFolder As Folder

Set olItems = Session.GetDefaultFolder(olFolderInbox).Items
Set inboxFolder = Session.GetDefaultFolder(olFolderInbox)

For i = olItems.count To 1 Step -1

Set olItem = olItems(i)

If olItem.Class = olMail Then

'Debug.Print olItem.subject
copyFlag = False

' What series
Set targetFolder = inboxFolder.folders("1.2. What")

If InStr(olItem.Categories, "Budget") Then
Set targetFolder = targetFolder.folders("1.2.3. Budget")
Set copyMail = olItem.Copy
copyFlag = True
copyMail.move targetFolder
End If


' Who series
Set targetFolder = inboxFolder.folders("1.5. Who")

If InStr(olItem.Categories, "John") Then
Set targetFolder = targetFolder.folders("1.5.1. John")
Set copyMail = olItem.Copy
copyFlag = True
copyMail.move targetFolder
End If

If copyFlag = True Then
olItem.Delete
End If

End If

Next

ExitRoutine:
Set olItems = Nothing
Set olItem = Nothing
Set inboxFolder = Nothing
Set targetFolder = Nothing
Set copyMail = Nothing

End Sub

With more knowledge you could be more efficient. Perhaps an array for categories on the item instead of hardcoding the category, maybe a loop instead of hardcoding folder names.