Results 1 to 2 of 2
  1. #1
    New Lounger
    Join Date
    Jun 2011
    Thanked 0 Times in 0 Posts

    Check to see if a DocVariable exists before running line of VBA code

    Is there a way to check to see if a docvariable exist before I run a line of code in vba?

    I currently do this with bookmarks using the following code:

    If ActiveDocument.Bookmarks.Exists("LumpSum") = True Then                 ActiveDocument.Variables("varProjCost").Value = .MostRecentProjDesc
    I do this because the document variable in the above code is within a bookmark that can be deleted if the person make a specific selection in a userform. So if the bookmark isn't there then the variable isn't there so I don't want to set its value.

    So I want to do the same with another variable but the variable isn't in a bookmark but could have been deleted by the userform. Is there a similar .Exists command for a docvariable?

    I'm trying to avoid errors.


  2. #2
    3 Star Lounger
    Join Date
    Feb 2001
    Willow Grove, Pennsylvania, USA
    Thanked 49 Times in 40 Posts
    First, the literal answer to your question: No, there is nothing for the .Variables collection that works like the .Bookmarks.Exists() method.

    Next, let's distinguish between a document variable (a member of the .Variables collection) and a DocVariable field that displays the value of a document variable. The document variable itself exists only in the memory space of the document, not on the document surface, so it can't be "within a bookmark". Your bookmark probably contains a { DocVariable varProjCost } field. The field may exist without the corresponding document variable, and vice versa.

    If a particular document variable doesn't exist, then the only thing your code can do with it that won't cause an error is to assign its value. If you need to do anything else when you aren't sure whether or not the variable exists, then you need to provide an error trap -- like this:

        Dim strVal As String
        ' ...
        On Error Resume Next
        strVal = ActiveDocument.Variables("varProjCost").Value
        If Err.Number = 0 Then
            MsgBox strVal
            MsgBox "Variable varProjCost does not exist"
        End If
        On Error GoTo 0  ' reset error handler
        ' ...
    Last, there's no harm in assigning a value to a document variable even if the DocVariable field that would display its value has been deleted from the document. It just means that there's no display of the value, not that an error would occur.

Posting Permissions

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