Word macro, storing the current selection (VBA)

Go To StackoverFlow.com


I have a Word document that contains about 4000 form fields which I have to export afterwards to a database. The matter is that none of the 4000 fields have an information in the "Bookmark" field, thus I cannot get the information stored in them.

I'm trying to create a macro to help the process of writing the bookmark (FormField.Name) but cannot manage to do it right. The matter is that I want to change the names of the FormFields contained in the user's selection, and only them. I've managed to come to this solution:

Sub Macro2()
    Dim myFile As String
    Dim fnum As Integer
    Dim sFileText As String
    Dim currentField As FormField

    myFile = "c:\testMacro.txt"
    fnum = FreeFile()
    Open myFile For Input As fnum

    For Each currentField In Selection.FormFields
        Input #fnum, sFileText

        With currentField
            .StatusText = sFileText
            .OwnStatus = True
        End With

        Application.WordBasic.FormFieldOptions Name:=sFileText
    Next currentField
End Sub

But it doesn't work, because the Selection object is changed in the For Each loop and afterwards it only contains the first FormField of the selection.

So here is my question, is there a way to save the current selection and load it back after having changed it.

I've tried :

Dim mySelection as Selection
Set mySelection = Selection

But if I change the Selection, the variable mySelection changes as well (which is quite normal...) and I didn't find any way to clone the object.

Has someone an idea on how to do this?


2009-06-16 10:05
by Gimly


Use a different reference for your "copy":

Dim selBkUp As Range
Set selBkUp = ActiveDocument.Range(Selection.Range.Start, Selection.Range.End)

Or use a duplicate:

Dim selBkUp As Range
selBkUp = Selection.Range.Duplicate
2009-06-16 11:04
by guillermooo


Selection.Range is automatically a duplicate, so you can just do:

Dim selBkUp As Range
Set selBkUp = Selection.Range
2014-10-05 15:20
by clum