简体   繁体   中英

Move emails from one Outlook folder to another

I am running this code to copy the contents from Outlook folder TODO to Outlook folder Test. Both folders exist.

I got

"Run-time error '-2147221233 (8004010f)'

for Set myItem = myInbox.Folders("TODO")

I tried

Dim myItem As Folder

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("test") 
    Set myItem = myInbox.Folders("TODO") 
    While TypeName(myItem) <> "Nothing" 
        myItem.Move myDestFolder 
        Set myItem = myItems.FindNext 
    Wend 
End Sub

This will move all the Files from TODO to Test

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("test")

 Set myItems = myInbox.Folders("TODO").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

You had to loop all the items in the folder, that code was for Finding a particular mail.

Reason why we used the Loop Backwards (Courtesy: @ComputerVersteher) If you loop forward and remove an item (eg first one), the following items takes over position from their predecessors (eg second-one gets first-one) and Collection.Count is decreased by one. Forward loop would try to fetch items up to starting Collection.Count , but the item with last index isn't available any longer. When moving backward, you start with the last item and if you remove it, the next item (index-1) is still available as it retains position. Btw, For Each loops produce strange results too and should be avoided when deleting items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM