VBA Excel - 宏告诉我Word文档即使未打开也是开放的

时间:2016-08-19 18:34:24

标签: vba excel-vba ms-word macros excel

首先,我在VBA Excel中有一个功能,告诉我Word文档是打开还是不打开。出于测试目的,我没有Word文档打开并期望“错误”#39;被退回。

Function IsFileOpen(filename As String) As Boolean
        Dim filenum As Integer, errnum As Integer

        On Error Resume Next   ' Turn error checking off.
        filenum = FreeFile()   ' Get a free file number.
        ' Attempt to open the file and lock it.
        Open filename For Input Lock Read As #filenum
        Close filenum          ' Close the file.
        errnum = Err           ' Save the error number that occurred.
        On Error GoTo 0        ' Turn error checking back on.

        ' Check to see which error occurred.
        Select Case errnum

            ' No error occurred.
            ' File is NOT already open by another user.
            Case 0
             IsFileOpen = False

            ' Error number for "Permission Denied."
            ' File is already opened by another user.
            Case 70
                IsFileOpen = True

            ' Another error occurred.
            Case Else
                Error errnum
        End Select

    End Function

叫做Via:

...
If IsFileOpen("C:/Temp/test.docx") = True Then
 MsgBox objWord.ActiveDocument.Name & " already open" 'ERROR FROM PIC HERE
 Set objDoc = objWord.ActiveDocument
Else
 Set objDoc = objWord.Documents.Open("C:/Temp/test.docx", Visible:=True)
End If
...

然而,当运行代码时,我得到文档是打开的(从案例70的IsFileOpen函数返回True)但是我在' objWord.ActiveDocument.Name'没有文件是开放的

enter image description here

在Windows 7任务管理器上,这就是我所拥有的。 Word应用程序已关闭,但似乎有Word的后台进程打开。但是,我会关闭所有我不会使用的文档,因此这些过程不应该运行

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为更好的测试来检查您的Word文件是否打开是使用实际的Word文档集合

因此,对于您的示例,请使用以下内容:

    With objWord
       For Each doc In .Documents 
          If doc.Name = "test.docx" Then 
              found = True 
              Exit For
          End If
       Next doc 
       If found <> True Then 
          .Documents.Open FileName:="C:/Temp/test.docx" 
       Else 
          .Documents("test.docx").Activate 
       End If
   End With