0
votes

In VBA for Word 2007, I want to be able to open a document, highlight sections of text and replace those sections with fields linked to a docvariables. The process would be:

  1. Open document.
  2. Select text.
  3. Select docvariable from list.
  4. Insert field linked to selected docvariable.
  5. Repeat steps 1-4 as required.

There is no way to know beforehand what the text to be selected is or which docvariable is going to be linked to which field or how many times these steps are going to be repeated.

Only with Microsoft could the most absolutely fundamental, simple task of allowing the user to make a selection at run-time and pass this selection back to sub-routine be so tortuous and surreal. I have spent 2 days trying to figure this out. If anyone can help, I will name my next child after you.

1
While I don't know how to fix your problem, I understand 'tortuous and surreal'.Lance Roberts

1 Answers

1
votes

I think "tortuous and surreal" is a misconception.

Create a small form with a dropdown (named "selVarName", for example) that lets you select all document variable names available. Link the form to a custom button in the Quick Access Toolbar.

Upon clicking "OK" in this form do something like this:

Private Sub btnOK_Click()
  Dim v As Word.Variable
  Dim n As String

  n = Me.selVarName.Value
  With Selection
    For Each v In .Document.Variables
      If v.Name = n Then v.Delete: Exit For
    Next v
    .Document.Variables.Add n, .Range.Text
  End With
End Sub

And this has bells and whistles already. You can do additional checking like "no text selected", for example.