"If" fails when no Item of "Body" exists but works with additional line - Need help understanding why

When this code checks a document that does NOT have an Item of “Body” it fails and throws the error: “Object variable not set”. I would think that if docMain did not have the Item “Body” that the If statement would process the Else part.

If docMain.HasItem(“Body”) Then

Set itemBody = docMain.GetFirstItem("Body")	'get the Subject item of the main document

... do some processing ...

Print #outputFile, itemBody.Text 

Else

Print #outputFile, "*** NO BODY TEXT IN EMAIL ***" 

End If

The If statement works when I copy the “Set itemBody” line and place it before the If statement as below:

Set itemBody = docMain.GetFirstItem(“Body”)

If docMain.HasItem(“Body”) Then

Set itemBody = docMain.GetFirstItem("Body")	'get the Subject item of the main document

... do some processing ...

Print #outputFile, itemBody.Text 

Else

Print #outputFile, "*** NO BODY TEXT IN EMAIL ***" 

End If

Why is it working this way?

I would think that if docMain does not have the Item “Body” that the If statement would process the Else part without the need of the additional Set statement (and why does it need to be before the If?).

Thanks for all your help!

Subject: “If” fails when no Item of “Body” exists but works with additional line - Need help understanding why

That’s weird.

How about recoding the if statement? Try:

If Not( docMain.GetFirstItem(“Body”) Is Nothing ) Then

… do some processing …

Print #outputFile, docMain.GetFirstItem( “Body” ).Text

Else

Print #outputFile, “NO BODY TEXT IN EMAIL

End If