0

我写了一个 Outlook 宏,它假设是:检查收件箱中未读电子邮件的主题,以获取采购订单号。如果它找到一个采购订单号,它会在一个 Excel 文件中查找相关的电子邮件地址。(我们卖家的邮箱),如果它找到一个邮箱地址,未读的邮件会被转发到那个地址,邮件会被标记为已读。

该代码在第一次遇到主题中带有 PO 编号的未读电子邮件地址时运行良好。问题是代码没有继续 for 循环。相反,我收到一条错误消息,提示“元素已被移动或删除”。我 99% 确定问题在于,在第一次遇到满足所有条件的邮件后,for 循环没有按照应有的方式继续。为了确定,我将发布整个代码。一如既往,非常感谢您随时查看我的问题!

Sub ForwardMail()

On Error GoTo eh:

'Initalizing Excel related variables and instances'
Dim xlApp As Object
Dim XlBook As Excel.Workbook

Set xlApp = CreateObject("Excel.Application")
xlApp.Application.Visible = True
Set XlBook = xlApp.Workbooks.Open("My path")

Dim Mailadress As Variant
Dim PoSheet As Excel.Worksheet
Set PoSheet = XlBook.Sheets("SheetName")
'End  Initalizing Excel related variables and instances

'Initalizing Outlook related variables and instances
Dim ns As Outlook.NameSpace
Dim folder As MAPIFolder
Dim item As Object
Dim MailToForward As MailItem

Set ns = Session.Application.GetNamespace("MAPI")
Set folder = ns.Folders("Example@mail.com").Folders("Inbox")
'Slutt initialisering Outlook relatert

Dim PoNumber As Double

'Loop through the items in the inbox folder
For Each item In folder.Items
    DoEvents
    If (item.Class = olMail) And (item.UnRead) Then
        'Find PO number from the subject
        PoNumber = CDbl(FinnPo(item.Subject))

        'If Po number is found, find email adress, using PO number
        If PoNumber <> 0 Then

            'Find email adress in excel file
            Mailadress = xlApp.VLookup(PoNumber, PoSheet.Range("C:D"), 2, False)

            'If mailadress variable is not an error, forward unread email to mailadress.
            If IsError(Mailadress) = False Then
                Set MailToForward = item.Forward
                MailToForward.To = Mailadress
                MailToForward.Send

                'Set mail property as read
                MailToForward.UnRead = False

            Else

            End If

        End If

    End If

Next

XlBook.Close
xlApp.Quit

MsgBox "Macro finished"

Exit Sub

eh:
    MsgBox Err.Description, vbCritical, Err.Number

End Sub

Function FinnPo(Subject As String) As String

    Dim find As String
    Find = "4500"

    Dim Location As Integer
    Location = InStr(Subject, Find)

    If Location <> 0 Then
        FinnPo = Mid(Subject, Location, 10)
    Else
        FinnPo = "0"
    End If

End Function
4

1 回答 1

0

所以很多谷歌搜索终于解决了我的代码问题。我发送邮件的事实MailToForward意味着该项目不再存在。因此,我不得不将变量的初始化移到循环中。我还必须item.Unread在发送后标记,而不是在那个时候不再存在的 MailItem。希望帮助其他有类似问题的人:MailItems 在发送后停止存在。

于 2013-07-05T22:03:58.600 回答