【问题标题】:Word macro, storing the current selection (VBA)Word 宏,存储当前选择(VBA)
【发布时间】:2009-06-16 10:05:40
【问题描述】:

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

我正在尝试创建一个宏来帮助编写书签 (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

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

所以这是我的问题,有没有办法保存当前选择并在更改后重新加载它。

我试过了:

Dim mySelection as Selection
Set mySelection = Selection

但是如果我更改了 Selection,变量 mySelection 也会发生变化(这很正常……),我没有找到任何克隆对象的方法。

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

谢谢

【问题讨论】:

    标签: vba ms-word


    【解决方案1】:

    为您的“副本”使用不同的参考:

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

    或使用重复:

    Dim selBkUp As Range
    selBkUp = Selection.Range.Duplicate
    

    【讨论】:

      【解决方案2】:

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

      Dim selBkUp As Range
      Set selBkUp = Selection.Range
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-03-22
        • 1970-01-01
        • 2013-02-23
        • 2015-10-17
        • 1970-01-01
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多