2016-08-19 111 views
0

要開始,我在VBA Excel中有一個函數,告訴我Word文檔是打開還是未打開。出於測試目的,我沒有Word文檔打開,並期望返回「False」。VBA Excel - 宏告訴我Word文檔即使未打開也是開放的

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 

調用途經:

... 
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 
... 

但運行代碼時,我得到的文件打開(返回真從IsFileOpen功能從案例70),但我得到「objWord.ActiveDocument錯誤。名稱」沒有打開文檔

enter image description here

在Windows 7任務管理器,這是我有。 Word應用程序已關閉,但似乎有Word的後臺進程打開。不過,我關閉所有文件,我不使用這樣這些進程不應運行

enter image description here

+0

什麼是調試器告訴你,如果你設置'如果IsFileOpen'一個斷點,單步執行代碼? –

+0

首先,您需要修復VBA中的對象問題 - 確保在退出VBA模塊時objWord完全相同並且被取消引用。看起來你會在幕後留下很多Word過程。因爲您沒有將Word設置爲可見,所以您無法看到它們手動關閉它們,並且因爲您沒有在代碼中放棄Word,所以它們仍然處於閒置狀態。 – dbmitch

+0

你有不同的Word實例(這可能是因爲你永遠不會關閉實例,只有文檔)。來自你的實例的'Documents'和來自這些實例的'Documents'是不同的'Documents'。但是,您的整個方法是錯誤的,並且根據您的實際目標,您需要關心自己的「Documents」或查看[GetObject](https://msdn.microsoft.com/en-us/library/辦公室/ gg251785.aspx)。 – GSerg

回答

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