Results 1 to 2 of 2
  1. #1
    Gold Lounger
    Join Date
    Dec 2000
    New Hampshire, USA
    Thanked 0 Times in 0 Posts

    Re: Office Collections: Better to Enumerate or Trap? (VBA Any)

    For those cases in which you know that it is just a true/false situation, just use the error trapping.
    Use a With ... End With to remove unnecessary object references.

  2. #2
    2 Star Lounger
    Join Date
    Jan 2004
    Mount Prospect, Illinois
    Thanked 0 Times in 0 Posts

    Office Collections: Better to Enumerate or Trap? (VBA Any)

    I've always been peeved by the lack of tidy orthogonality to the built-in collections in VBA:
    With the exception of Word's Bookmarks collection (maybe there's a couple more, but not that I end up needing), there's no .Exists property.
    Combined with the fact that .Add won't let you set the value of an existing item, and setting the value won't let you add a new one if it's not there already, it gets frustrating.

    The general documentation advises enumerating a list before attempting to add or set a value, e.g.
    <pre>bFound = False
    For Each oVar In ActiveDocument.Variables
    If oVar.Name = sNewItem Then
    bFound = True
    Exit For
    End If
    Next oVar
    If bFound Then
    ActiveDocument.Variables(sNewItem) = sNewValue
    ActiveDocument.Variables.Add sNewItem, sNewValue
    End If</pre>

    This has always seemed tedious, even if encapsulated in a class (and you can't subclass the real Variables class in VBA anyway), and awfully slow, with those loops.
    I've always favored this method:

    <pre>on error resume next
    ActiveDocument.Variables(sNewItem) = sNewValue
    If Err.Number <> 0 Then
    ActiveDocument.Varlables.Add sNewItem, sNewValue
    End If
    On Error Goto 0

    What's the downside? Do I increase Word's instability at all with the error handling on a regular basis? Is it actually slower than enumerating 10, 100, 1000 items (OK, not many of the collections such as CustomProperties, Variables or Bookmarks will have 1000 items, but they could)?

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts