Word macro, storing the current selection (VBA)

北战南征 提交于 2019-12-10 15:23:17

问题


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


回答1:


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



回答2:


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

Dim selBkUp As Range
Set selBkUp = Selection.Range


来源:https://stackoverflow.com/questions/1000582/word-macro-storing-the-current-selection-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!