Word 宏,存储当前选择 (VBA)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1000582/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 10:29:29  来源:igfitidea点击:

Word macro, storing the current selection (VBA)

vbams-wordword-vba

提问by Gimly

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.

我有一个 Word 文档,其中包含大约 4000 个表单字段,之后我必须将这些字段导出到数据库。问题是 4000 个字段中没有一个在“书签”字段中包含信息,因此我无法获取存储在其中的信息。

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:

我正在尝试创建一个宏来帮助编写书签 (FormField.Name) 的过程,但无法做到正确。问题是我想更改用户选择中包含的 FormFields 的名称,并且只更改它们。我设法找到了这个解决方案:

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.

但它不起作用,因为在 For Each 循环中更改了 Selection 对象,之后它只包含选择的第一个 FormField。

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.

但是,如果我更改 Selection,变量 mySelection 也会更改(这是很正常的...)并且我没有找到任何方法来克隆该对象。

Has someone an idea on how to do this?

有人知道如何做到这一点吗?

Thanks

谢谢

回答by guillermooo

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

回答by clum

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

Selection.Range自动重复,所以你可以这样做:

Dim selBkUp As Range
Set selBkUp = Selection.Range