禁止在Word 2013 VBA脚本上执行不需要的跳转/滚动

时间:2014-11-12 14:46:19

标签: vba ms-word word-vba

在我的Word 2013文档中访问旧版表格字段值时(获取或设置):

' get
myField = ActiveDocument.FormFields("myField").Result

' set
ActiveDocument.FormFields("myField").Result = myValue

文档奇怪地向上/向上滚动并向上滚动并停在一个完全不同的位置(它似乎跳到引用字段所在的行)。

查看可以查看错误的this screencasta sample file

我用过

Application.ScreenUpdating = False

Sub

的开头
Application.ScreenUpdating = True

在我Sub的末尾,但不幸的是,这并没有帮助。

为了抑制这种行为,我需要修改什么?

2 个答案:

答案 0 :(得分:3)

我在Word MVP Site找到了解决方案的线索。正如您所指出的,问题是当您访问FormField对象的属性时,焦点将设置为此表单字段。即使通过VBA编辑器中的“本地窗口”浏览表单字段,也可以看到此行为。

不使用FormField对象,而是通过Result对象访问Bookmark属性。

更改此内容:

myField = ActiveDocument.FormFields("myField").Result

对此:

myField = ActiveDocument.Bookmarks("myField").Range.Fields(1).Result

现在,您可以访问此字段的值,而无需更改文档中的焦点。要在字段上设置值,您可以使用Text属性。

ActiveDocument.Bookmarks("myField").Range.Fields(1).Result.Text = myValue

希望这有帮助!! : - )

答案 1 :(得分:1)

如果您需要访问的只是结果字段,这是一个很棒的解决方法。遗憾的是,某些表单字段属性无法通过Bookmark集合间接访问,最明显的是StatusText。我正在使用formfields来构建在VBA代码中自动评分的测试,而StatusText是唯一允许您在每个表单字段中存储静态(非易失性)答案数据的字段(据我所知)。

这是我正在使用的代码示例。以下循环测试结果字段,以查看它们是否与StatusText字段中存储的答案匹配

For Each fld In oFormFields

    strResult = fld.Result
    strStatus = fld.StatusText

    If strStatus = strResult Then
        ' color answer green to show that it was correct
        fld.Range.Font.ColorIndex = wdBrightGreen
     Else
        ' color answer red to show that it was wrong
        fld.Range.Font.ColorIndex = wdRed
     End If
 Next fld 

我看不到用书签引用替换表单字段引用,但也许我错过了一些东西。