代码之家  ›  专栏  ›  技术社区  ›  magol Nathaniel Roark

在intranet上打开文档时访问VBA中的活动文档

  •  1
  • magol Nathaniel Roark  · 技术社区  · 14 年前

    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 回复  |  直到 9 年前
        1
  •  1
  •   Ben McCormack    14 年前

    在word2010中,我还没有使用Word事件模型,但是有几件事我可以看一下。

    New , Open ,和 Close 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 这种情况最终会发生的 不是 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 对象已设置。一旦对象被实例化,代码就可以向前移动。

        2
  •  1
  •   µBio    13 年前

    我也有同样的问题,我目前的解决办法是

    Private Sub Document_Open()
        Application.OnTime (Now + TimeValue("00:00:02")), "ProcessActiveDocument"
    End Sub
    
    Sub ProcessActiveDocument
        'ActiveDocument works here
    End Sub
    
        3
  •  0
  •   magol Nathaniel Roark    14 年前

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