I want to place a variable in a Word 2016 document and set it it. RRS feed

  • Question

  • I want to place a variable in a Word 2016 document and set it it. The value of this variable will then decide whether or not I include certain text. Similar to an ifdef statement in C header files.

    I was thinking of using IF fields in the document. But I can't figure out how to insert a variable and change it the value of the variable. I am using Word 2016

    Wednesday, December 28, 2016 9:37 PM

All replies

  • You could store the variable in a Document Variable or a Custom Document Property and have the IF field test that. For example, to create and/or update a Document Variable, you might use code like:

    Sub SetDocVar(StrVar As String, Val As String)
    With ActiveDocument
      On Error Resume Next
      .Variables.Add Name:=StrVar
      .Variables(StrVar).Value = Val
    End With
    End Sub

    You'd then call the above with code like:

    Sub Demo()
    Call SetDocVar("SomeVariable", "3")
    End Sub

    where SomeVariable is the variable name and 3 is its value (which could also be a text string).

    Although it's possible to both create and give a value to a Document Variable in one go, using code like:
    .Variables.Add Name:=StrVar, Value:=Val
    the code I posted caters both for the creation and updating of the variable. The 'On Error Resume Next' line is needed to prevent errors that would occur if you try to (re)create an existing variable.

    Having created/updated the variable, you can test its contents via an IF field coded along the lines of:

    {IF{DOCVARIABLE  SomeVariable}= 3 "Text for 3" "Text for NOT 3"}

    If you already have the field code set up in the body of the document, you could update it by adding one more line to the 'Demo' sub:

    Paul Edstein
    [MS MVP - Word]

    Wednesday, December 28, 2016 11:32 PM
  • Hi SS20161231,

    please refer the suggestion given by macropod can solve your issue.

    if you think that your issue is solved then mark his suggestion as an answer.

    if you have any further question then let us know about that.

    we will try to suggest you further for the same.



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Thursday, December 29, 2016 12:40 AM