PDA

View Full Version : VBA to move mail from Gmail 'Important' folder in Outlook to Inbox



riteoh
03-11-2023, 11:11 PM
I have set up Outlook to retrieve all of my gmail. Unfortunately however, most of the emails are going to the 'Important' folder, hidden in the [Gmail] folder.
I'm trying to write a macro to automatically move all mail from Important to Inbox, and have this code, but am getting an error. My experience in writing code is extremely poor, so I tend to google and then try to modify - which works out badly!!

My folder structure is (The folders inside the Gmail folder are the first 3)

Inbox
>[Gmail]
Important
Drafts
Sent Mail
......
Outbox
Search Folders
Can somebody indicate where I am going wrong? Thanks!!!


Sub MoveItems()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim myDestFolder As Outlook.Folder
Dim myItems As Outlook.Items
Dim myItem As Object
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set myDestFolder = myInbox.Folders("Important")
Set myItems = myInbox.Folders("Inbox").Items
'Debug.Print myItems.Count
For i = myItems.Count To 1 Step -1 'Iterates from the end backwards
myItems.Item(i).Move myDestFolder
Next
End Sub

Beethoven
03-12-2023, 06:52 AM
Help us to help you ... what EXACTLY is the error message?

On first glance, you have it backwards - you are moving from Inbox TO Important.

riteoh
03-12-2023, 02:49 PM
Thanks Beethoven,

Have swapped these two lines.

The code seems to stop at the line Set myDestFolder = myInbox.Folders("Inbox")

I am getting an error "The attempted operation failed. An object could not be found.

Could this be due to the Important folder not being a sub-folder of Inbox, but a subfolder of [Gmail]?

Thanks.

Beethoven
03-13-2023, 04:42 AM
Could this be due to the Important folder not being a sub-folder of Inbox, but a subfolder of [Gmail]?

Sounds reasonable. Drop a breakpoint and look at the data.

somit
05-22-2023, 10:52 PM
I don't know about VBA but you can configure Gmail to Outlook to move all items from Gmail mailbox to Outlook without any modification.