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

    Home » Forums » AskWoody support » Productivity software by function » MS Word and word processing help » Check to see if a DocVariable exists before running line of VBA code

    Author
    Topic
    #477344

    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:

    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.

    Thanks

    Viewing 0 reply threads
    Author
    Replies
    • #1284734

      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:

      Code:
          Dim strVal As String
          ‘ …
          On Error Resume Next
          strVal = ActiveDocument.Variables(“varProjCost”).Value
          If Err.Number = 0 Then
              MsgBox strVal
          Else
              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.

    Viewing 0 reply threads
    Reply To: Check to see if a DocVariable exists before running line of VBA code

    You can use BBCodes to format your content.
    Your account can't use all available BBCodes, they will be stripped before saving.

    Your information: