Ebbe
Ebbe

Reputation: 43

How can I by VBA code see that outlook object is closed

I use Outlook to edit the subject and body text using following code:

Sub SetupEmailTexts()
Dim olApp As Object
Dim olNameSpace As Object 'Outlook.NameSpace
Dim MailFolder As Object 'Outlook.MAPIFolder
Dim MyMail As Object 'Outlook.MailItem

GetSetup

Set olApp = CreateObject("Outlook.Application")
Set olNameSpace = olApp.GetNamespace("MAPI")
Set MailFolder = olNameSpace.GetDefaultFolder(16)
Set MyMail = MailFolder.Items.Add
MyMail.Display
MyMail.Subject = SubjectString
MyMail.HTMLBody = BodyString
MsgBox ("Edit subject and body before pressing OK")
If Not IsNull(MyMail) Then
    PutSubjectBody MyMail.Subject, MyMail.HTMLBody
    MyMail.Close olDiscard
End If
End Sub

If I close outlook before pressing OK in the message box produced by the code, i receive the runtime error "The remote server machine does not exist or is unavailable" in line "PutSubjectBody MyMail.Subject, MyMail.HTMLBody". As You can see I have tried to use IsNull to determine MyMail is still "alive" or not. What can I use instead of "IsNull"?

Upvotes: 1

Views: 261

Answers (2)

Alex K.
Alex K.

Reputation: 175936

In this case I would use an On Error, detect that specific Err.Number and handle it gracefully.

The closure of the automation object is not going to be reflected in the state of the MyMail variable itself, it would need to implement a IsConnectedToInstance property, and it does not.

You could wire up the event Outlook.Application.Quit but then you would need to check a flag and there would be cases when it gets missed.

Upvotes: 1

Gabi
Gabi

Reputation: 43

You can try to use error handling -

add the line in the beginning of the sub

On Error goto err

add on the end of the sub:

NoError:
  exit sub

err:
    msgbox "you closed outlook. couldn't do my thing"

Upvotes: 0

Related Questions