Normal.dotm宏抛出错误打开受保护的文档

时间:2012-08-20 11:52:02

标签: ms-word word-vba

我将以下宏添加到我的Normal.dotm for Word 2010中:

Sub AutoOpen()
'
' AutoOpen Macro
'
'
   Dim aStory As Range
   Dim aField As Field

   For Each aStory In ActiveDocument.StoryRanges

      For Each aField In aStory.Fields
         aField.Update
      Next aField

   Next aStory

 ' set document as unchanged (prevents save dialog popping up when closing) - further changes will set this back
 ActiveDocument.Saved = True
End Sub

现在,当我在Word 2010中打开某些文档时,收到以下错误消息:

  

运行时错误'4248'

     

此命令不可用,因为没有文档打开

到目前为止,这似乎发生在受保护视图中打开的文件(例如从互联网下载的文件或电子邮件附件) - 如果我在信任中心关闭受保护的视图,则问题就会消失。

1 个答案:

答案 0 :(得分:3)

Microsoft在detecting whether Protected Mode is running from within a macro上写了一篇博客文章。

这表明当受保护的视图中的文档时,Application.ActiveProtectedViewWindow的值为Nothing。因此,在If语句中检查引用ActiveDocument的宏函数时,如果文档处于受保护的视图中,则会阻止这些函数运行。

以上脚本变为:

Sub AutoOpen()
    '
    ' AutoOpen Macro
    '
    '
       Dim aStory As Range
       Dim aField As Field

    ' Check that document is not in Protected View before doing anything
    If Application.ActiveProtectedViewWindow Is Nothing Then

           For Each aStory In ActiveDocument.StoryRanges

              For Each aField In aStory.Fields
                 aField.Update
              Next aField

           Next aStory

         ' set document as unchanged (prevents save dialog popping up when
         'closing) - further changes will set this back
         ActiveDocument.Saved = True
    End If
End Sub