I have this code for sending emails via Outlook. I saw it somewhere and made some changes.
Code:
Public Sub EnviarEmail(strEmail As String, strAsunto As String, srtCuerpoEmail As String, Optional strAdjunto As String)
Dim olApp As Object
Dim objMail As Object
Dim aArchivosAdjuntos() As String
On Error Resume Next 'Keep going if there is an error
Set olApp = GetObject(, "Outlook.Application") 'See if Outlook is open
If Err Then 'Outlook is not open
Set olApp = CreateObject("Outlook.Application") 'Create a new instance of Outlook
End If
'Create e-mail item
Set objMail = olApp.CreateItem(olMailItem)
With objMail
'Set body format to HTML
.BodyFormat = olFormatHTML
.To = strEmail
.Subject = strAsunto
.HTMLBody = srtCuerpoEmail
If Not IsNull(strAdjunto) Then
aArchivosAdjuntos = Split(strAdjunto, ";")
For i = LBound(aArchivosAdjuntos) To UBound(aArchivosAdjuntos)
.Attachments.Add aArchivosAdjuntos(i), olByValue, , "My Displayname"
Next i
End If
.Send
End With
Set olApp = Nothing
Set objMail = Nothing
MsgBox "Email enviado con éxito"
End Sub
It works fine, but when I send many emails, by the third or forth mail, it crashes. Access stays blocked and Outlook remains closing for a long time. Finally I always have to reset.
Could it be that I try run the instance and it crashes because the object is still closing? How can I avoid this crash??
Should I use "do events" while busy?
I am running Windows Vista in "that" computer.