0
我寫了一個Outlook宏,它假設:檢查收件箱中未讀郵件的主題,以獲取採購訂單編號。如果找到採購訂單編號,它會在excel文件中查找關聯的電子郵件地址。 (我們的賣家的電子郵件),如果它找到一個電子郵件地址,未讀的電子郵件被轉發到該地址,郵件標記爲已讀。用於循環錯誤的VBA Outlook宏
代碼首次在主題中遇到帶有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("[email protected]").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