Suppress unwanted jumping/scrolling on Word 2013 VBA Script

混江龙づ霸主 提交于 2019-12-17 21:12:41

问题


When accessing Legacy Form Field values in my Word 2013 document like this (getting or setting):

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

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

the document weirdly jumps/scrolls down and up and stops at a complete different position (it seems to jump to the lines where the referred fields are positioned).

Have a look at this screencast or a sample file where the error can be viewed.

I have used

Application.ScreenUpdating = False

at the beginning of my Sub and

Application.ScreenUpdating = True

at the end of my Sub but unfortunately this doesn't help.

What do I have to modify in order to suppress this behaviour?


回答1:


I found a clue to the solution on the Word MVP Site. Like you pointed out, the issue is when you access the properties of a FormField object, the focus is set to this form field. You can see this behavior even when browsing the form fields through the Locals Window in the VBA editor.

Instead of using the FormField object, access the Result property through the Bookmark object.

Change this:

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

To this:

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

Now you can access the value of this field without changing the focus in your document. To set a value on a field, you can use the Text property.

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

Hope this helps!! :-)




回答2:


This is a fantastic workaround if all you need to access is the Result field. Unfortunately, some of the form field properties are not accessible indirectly through the Bookmark collection, most notably StatusText. I am using formfields to build tests that are graded automatically in VBA code, and StatusText is the only field (to my knowledge) that allows you to store static (non-volatile) answer data in each form field.

Here's a sample of the code I am using. The following loop tests the Result fields to see if they match the answers stored in the StatusText field

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 

I see no way of replacing the form field references with bookmark references, but perhaps I am missing something.



来源:https://stackoverflow.com/questions/26889709/suppress-unwanted-jumping-scrolling-on-word-2013-vba-script

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