在Intranet上打开文档时,在VBA中访问Active Document

时间:2010-08-30 12:26:27

标签: javascript vba ms-word word-vba

我们有最初为Word 97编写的旧Word模板。对于每个新版本,我们都更新了模板。现在我们将从Word 2003转到Word 2010,当然还有问题。

该模板包含以下代码:

Private Sub Document_Open()
    On Error Resume Next
    If ActiveDocument.Type = wdTypeDocument Then
        ' Update the document from database'
    End If
End Sub

问题是ActiveDocument给出了错误

  

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

在Intranet上使用脚本打开文档:

<a href="javascript:opendokument('P:\\01\\2-010-01.doc')">012-010-01</a>
<SCRIPT language=javascript> 
function opendokument(dokument){
var objAppl;;

try{
    objAppl = GetObject("","Word.Application");
    objAppl.Documents.open(dokument);
}
catch(exception){
    objAppl = new ActiveXObject("Word.Application");
    objAppl.Visible = true;
    objAppl.Documents.open(dokument);
}   
objAppl = null; 
}
</script>

如果我从本地计算机运行脚本或通过Windows打开文档,我不会收到错误

3 个答案:

答案 0 :(得分:1)

我没有使用过Word 2010中的Word事件模型,但我看到的内容很少。

首先,看看是否还有其他可以挂钩的事件。在Word 2000中,我只看到NewOpenClose。也许在Word 2010中,还有其他事件,例如Loaded?如果是这样,您可以尝试将代码放在其中一个肯定已经加载文档的事件中。

否则,您可能会编写一些“等待”的代码,直到将ActiveDocument设置为对象实例。您可以尝试这样的事情:

Private Sub Document_Open()

  Do While ActiveDocument Is Nothing
    DoEvents
  Loop

  If ActiveDocument.Type = wdTypeDocument Then
    Debug.Print "Now the document is open"
  End If

End Sub

循环中的DoEvents应允许加载文档,While条件最终会捕获ActiveDocument不是Nothing并允许程序继续。当然,这假设文档实际上会变得开放,但这是值得尝试的。要了解此代码的工作原理,请查看以下代码:

Private Sub Document_Open()

Dim dtmLater As Date
Dim doc As Document

dtmLater = DateAdd("s", 5, Now())

  Do While doc Is Nothing
    DoEvents
    If Now() >= dtmLater Then
      Set doc = ActiveDocument
    End If
  Loop

  If ActiveDocument.Type = wdTypeDocument Then
    Debug.Print "Now the document is open"
  End If

End Sub

上面的代码任意暂停5秒,这样你就可以看到代码循环,直到doc对象被设置为止。一旦对象被实例化,代码就可以向前移动。

答案 1 :(得分:1)

我遇到了同样的问题,我现在的狡猾解决方案是

Private Sub Document_Open()
    Application.OnTime (Now + TimeValue("00:00:02")), "ProcessActiveDocument"
End Sub

Sub ProcessActiveDocument
    'ActiveDocument works here
End Sub

答案 2 :(得分:0)

我确实将Intranet服务器添加到Internet Explorer中的本地Intranet区域。然后我将“初始化并编写未标记为安全脚本的ActiveX控件脚本”设置为“已启用”。