Word and the IsObjectValid Function

Filed under Office

One thing that can be maddening about programming against the Word Object Model is that objects have a habit of “disappearing” on you.

Say you retrieve a range, retrieve the fields in that range, then delete the range.

You still have references to those fields, but they no longer actually exist. Attempting to access any of the properties or methods on a field in this condition will cause Word to throw an exception with the message “That object has been deleted”.

Most code I’ve seen tends to handle these kinds of situations in one of two ways…

  1. Attempt to write the code such that if you’ve caused an object to become “deleted” that you simply don’t access it after that point. Sometimes this is easier said than done.
  2. Just wrap access to the object in a Try Catch, or On Error Resume Next. Test for any error condition and react accordingly. However, this has that nasty “the normal flow of code is through an exception” code smell. Not pretty.

Fortunately, there is third way.

The Word APPLICATION object has a function tucked away on it, called, appropriately enough, “IsObjectValid”.

Pass it a Word object model object and it’ll pass back true if the object is valid, or false if it’s been deleted.

Dim Rng = WordApp.Content
Dim Fld = Rng.Fields(1)
If WordApp.IsObjectValid(Fld) Then
   Debug.Print Fld.Code.Range.Text
   'the FLD object is no longer valid
End If

Yes, it’s been around for a good long while so this may not be news to everyone, but it’s a handy trick to have in your toolbox if you work with Word regularly.

Post a Comment

Your email is never published nor shared. Required fields are marked *