问题
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
回答1:
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 (e.g. first one), the following items takes over position from their predecessors (e.g second-one gets first-one) andCollection.Count
is decreased by one. Forward loop would try to fetch items up to startingCollection.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.
来源:https://stackoverflow.com/questions/56990440/move-emails-from-one-outlook-folder-to-another