迭代多个选择/文件夹项目

时间:2018-03-07 00:02:46

标签: vba outlook outlook-vba

我看了MailItem并且没有看到任何表明我可以转移选择项目的内容。

我的代码功能正常,Set objItem = GetCurrentItem()行只需要一封邮件。

我希望ForEach通过文件夹,或ForEach通过选择。

我试过像

这样的东西
Sub ListMailsInFolder()
Dim objNS As Outlook.NameSpace
Dim objFolder As Outlook.MAPIFolder

Set objNS = GetNamespace("MAPI")
Set objFolder = objNS.Folders.GetFirst ' folders of your current account
Set objFolder = objFolder.Folders("Foldername").Folders("Subfoldername")

For Each Item In objFolder.Items

我不知道自己在做什么。

以下是我试图在多封电子邮件上执行的代码:

Sub HelpdeskNewTicket()
Dim helpdeskaddress As String
Dim objMail As Outlook.MailItem
Dim strbody As String
Dim oldmsg As String
Dim senderaddress As String
Dim addresstype As Integer

' Set this variable as your helpdesk e-mail address
helpdeskaddress = "danielbelamiinc@gmail.com"

Set objItem = GetCurrentItem()
Set objMail = objItem.Forward

' Sender E=mail Address
senderaddress = objItem.SenderEmailAddress

strbody = objItem.Body

objMail.To = helpdeskaddress
objMail.Subject = objItem.Subject
objMail.Body = strbody

'Automatically Send the ticket
objMail.Send

Set objItem = Nothing
Set objMail = Nothing
End Sub


Function GetCurrentItem() As Object
Dim objApp As Outlook.Application
Set objApp = Application
On Error Resume Next
Select Case TypeName(objApp.ActiveWindow)
Case "Explorer"
Set GetCurrentItem = _
objApp.ActiveExplorer.Selection.Item(1)
Case "Inspector"
Set GetCurrentItem = _
objApp.ActiveInspector.CurrentItem
Case Else
End Select
End Function

1 个答案:

答案 0 :(得分:1)

要循环选择项目,请使用For...Next Statement Loop [MSDN]

语法

  

For counter = initial_value To end_value [Step step-counter]

<强> Example on Selection Items

Option Explicit
Public Sub Example()
    Dim Item As Outlook.mailitem
    Dim i As Long

    For i = ActiveExplorer.Selection.Count To 1 Step -1
    Set Item = ActiveExplorer.Selection.Item(i)
        Debug.Print Item.Subject
        ' Call Sub
    Next
End Sub

文件夹项目示例

Option Explicit
Public Sub Example()
    Dim Inbox As Outlook.folder
    Set Inbox = Application.Session.GetDefaultFolder( _
                                    olFolderInbox _
                                    )


    Dim Items As Outlook.Items
    Set Items = Inbox.Items

    Dim i As Long
    For i = Items.Count To 1 Step -1
        DoEvents
        Debug.Print Items(i) 'Print on Immediate Window
    Next
End Sub

DoEvents MSDN&amp; Debug.Print SO Link

  

说明
  循环执行给定次数,由循环计数器确定。要使用For ... Next循环,必须将数值赋给计数器变量。在循环的每次迭代中,该计数器自动递增或递减。在For语句中,指定最初分配给计数器的值以及计数器将要执行的代码块的最大值。 Next语句标记要重复执行的代码块的结束,并且还用作表示要修改计数器变量的一种标志。

     

<强> CurrentFolder Property

  

返回或设置一个MAPIFolder对象,该对象表示资源管理器中显示的当前文件夹。使用此属性可更改用户正在查看的文件夹。