I am working on a "mail bot", where I will receive a filled template, and populate and save an Excel file with that information.
I can fill the first file and quit the Excel file.
When a second mail arrives, I get
'1004 - application-defined or object-defined error'
Why am I getting the error on the second and beyond ones?
I am running the code when a new mail arrives
Option Explicit
Private WithEvents inboxItems As Outlook.Items
Private Sub Application_Startup()
Dim outlookApp As Outlook.Application
Dim objectNS As Outlook.NameSpace
Set outlookApp = Outlook.Application
Set objectNS = outlookApp.GetNamespace("MAPI")
Set inboxItems = objectNS.GetDefaultFolder(olFolderInbox).Items
End Sub
The main sub
Private Sub inboxItems_ItemAdd(ByVal Item As Object)
On Error GoTo ErrorHandler
Dim Msg As Outlook.MailItem
Dim MessageInfo
Dim Result
Dim splitter() As String
Dim splitter2() As String
Dim str As Variant
Dim LoopCali As Integer
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceWS As Worksheet
Dim strFile As String
If TypeName(Item) = "MailItem" Then
If InStr(Item.Subject, "BOT") > 0 Then
splitter = Split(Item.Body, vbCrLf)
splitter2 = Split(splitter(40), "-")
Set xlApp = CreateObject("Excel.Application")
strFile = "C:\Users\e1257539\Desktop\SMOBOT\SMO_TOOL_BOT.xlsm"
With xlApp
.Visible = TRUE
.EnableEvents = FALSE
End With
Set sourceWB = Workbooks.Open(strFile, , False, , , , , , , True)
sourceWB.Activate
With xlApp
.Worksheets("HEADER").Range("D6").Value2 = splitter(22)
.Worksheets("HEADER").Range("D8").Value2 = splitter(12)
.Worksheets("HEADER").Range("F4").Value2 = "AINT"
.Worksheets("HEADER").Range("F3").Value2 = "EXW"
.Worksheets("HEADER").Range("C2").Value2 = Worksheets("QuoteSTG").Range("A" + CStr(Worksheets("QuoteSTG").Range("B1").Value2)).Value2
.Worksheets("QuoteSTG").Range("A" + CStr(Worksheets("QuoteSTG").Range("B1").Value2)).Value2 = ""
End With
If splitter(2) = "Calibração" Then
Result = MsgBox(splitter(2), vbOKOnly, i)
LoopCali = splitter(26)
End If
If splitter(2) = "Trainamento" Then
End If
End If
MessageInfo = "" & _
"Sender : " & Item.SenderEmailAddress & vbCrLf & _
"Sent : " & Item.SentOn & vbCrLf & _
"Received : " & Item.ReceivedTime & vbCrLf & _
"Subject : " & Item.Subject & vbCrLf & _
"Size : " & Item.Size & vbCrLf & _
"Message Body : " & vbCrLf & Item.Body
End If
xlApp.Quit
Set xlApp = Nothing
Set sourceWB = Nothing
Set sourceWS = Nothing
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
xlApp.Quit
Set xlApp = Nothing
Set sourceWB = Nothing
Set sourceWS = Nothing
'Resume ExitNewItem
End Sub