英文:
Calling a specific item in an indexed For loop
问题
在对象上进行迭代的 For Each 循环与在索引 For 循环中调用特定项之间的区别是什么?
我编写了第一个宏,它按预期工作,但会提前退出。我认为这是因为我正在对迭代的列表进行更改。为了解决这个问题,我从列表底部开始工作,但调用 item(i) 并不返回一个对象。
在列表中间部分退出的代码。
Sub MoveItems()
'...(代码未变)
For Each olMail In myItems
If InStr(olMail.HTMLBody, "Some Tag") <> 0 Then
olMail.Move triaged_emails_A
Else
olMail.Move triaged_emails_B
End If
Next
End Sub
尝试修复上述失败的代码,但我无法将特定项调用为对象。
Sub MoveItems()
'...(代码未变)
For i = myItems.Count To 1 Step -1
Set olMail = myInbox.Items(i)
If InStr(olMail.HTMLBody, "Some Tag") <> 0 Then
olMail.Move triaged_emails_A
Else
olMail.Move triaged_emails_B
End If
Next
End Sub
上述代码会触发 Set olMail = myInbox.item(i)
这一行,并返回:
需要对象。
英文:
I’m trying to understand the difference between iterating an object in a For Each loop vs calling a specific item in an indexed For loop.
I wrote the first macro which works as expected except it exits prematurely. I think because I’m making changes to the list I’m iterating on. To fix this I worked from the bottom of the list up but calling item(i) does not return an object.
Code that exited part way through the list.
Sub MoveItems()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim traiged_emails_A As Outlook.Folder
Dim traiged_emails_B As Outlook.Folder
Dim myItems As Outlook.Items
Dim olMail As Variant
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set triaged_emails_A = myInbox.Folders("triaged_emails_A")
Set triaged_emails_B = myInbox.Folders("triaged_emails_B")
Set myItems = myInbox.Folders("triaged_emails").Items
For Each olMail In myItems
If InStr(olMail.HTMLBody, "Some Tag") <> 0 Then
olMail.Move triaged_emails_A
Else
olMail.Move triaged_emails_B
End If
Next
End Sub
Code that attempts to fix the above failure but I can’t call the specific item as an object.
Sub MoveItems()
Dim myNameSpace As Outlook.NameSpace
Dim myInbox As Outlook.Folder
Dim traiged_emails_A As Outlook.Folder
Dim traiged_emails_B As Outlook.Folder
Dim myItems As Outlook.Items
Dim olMail As Variant
Set myNameSpace = Application.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myItems = myInbox.Items
Set triaged_emails_A = myInbox.Folders("triaged_emails_A")
Set triaged_emails_B = myInbox.Folders("triaged_emails_B")
Set myItems = myInbox.Folders("triaged_emails").Items
For i = myItems.Count To 1 Step -1
Set olMail = Inbox.Items(i)
If InStr(olMail.HTMLBody, "Some Tag") <> 0 Then
olMail.Move triaged_emails_A
Else
olMail.Move triaged_emails_B
End If
Next
End Sub
The above hits the line Set olMail = myInbox.item(i)
and returns
>Object Required.
答案1
得分: 1
将以下行替换为:
Set olMail = myItems(i)
或者
Set olMail = myItems.Item(i)
英文:
Replace the line
Set olMail = Inbox.Items(i)
with
Set olMail = myItems(i)
or
Set olMail = myItems.Item(i)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论