tags:

views:

1003

answers:

1

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  A: 

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.

Tomalak
The problem I have is with the selection object. Everything I can find appears to require the text to be already selected or to rely on searching the documentfrom within the macro. I need the program to prompt the user to make a selection at runtime by highlighting text. How do I do this?
david
What's wrong with letting the user select some text and click a button afterwards? I guess I still don't understand what you are trying to do, but I have the gut feeling that the *way* you try to do it may be the wrong one.
Tomalak