Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Word macro, storing the current selection (VBA)

Tags:

ms-word

vba

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

        currentField.Select
        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?

Thanks

like image 316
Gimly Avatar asked Jun 16 '09 10:06

Gimly


1 Answers

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
like image 91
guillermooo Avatar answered Sep 19 '22 08:09

guillermooo