2016-10-26 67 views
0

我有一個VBA子工具,用於檢查工作簿是否打開,然後將數據從其他工作簿複製並粘貼到其中。這是在application.ontime循環中自動完成的。當我處理其他事情時,我通常會將其最小化,並偶爾檢查Excel數據複製/粘貼。 Excel會不時彈出一個框,說明目標工作簿已打開,並詢問是否要重新打開它。在彈出的時間和檢查工作簿的時間之間錯過了許多子運行。如何使用VBA自動接受Excel提示?

代碼在哪裏出現問題:

If dataset Is Nothing Then 
    Set dataset = Workbooks.Open("C:\Users\Ken\Desktop\Df.xlsx") 
Else 
    Set dataset = Workbooks("Df.xlsx") 
End If 

我能做些什麼讓Excel自動處理這種情況呢?

第二個問題:我懷疑它可能與事實有關,因爲我可能在運行之間觸摸了工作簿而沒有保存它,導致Excel認爲自上次保存以來發生了更改。有人可以評論,如果這可能是一個原因?

+0

你能看到什麼行實際上導致excel彈出嗎?在我的Excel 2013中,如果我嘗試設置工作簿變量以打開已打開的工作簿,則只需將其設置爲已打開的工作簿並且不會彈出 – user3598756

+0

@ user3598756我剛剛在Excel 2016中對其進行了測試。如果嘗試打開另一個工作簿兩次它不會拋出錯誤,但如果您嘗試打開正在調用該代碼的工作簿,則會出現彈出窗口(例如'Workbooks.Open ThisWorkbook.FullName')。 –

+0

@ user3598756感謝您指出。 –

回答

2

首先檢查工作簿是否已打開。如果打不開,請嘗試打開它。這可以在下面的代碼中完成。請參考link

Sub TestFileOpened() 
    Dim fullPath As String 

    fullPath = "C:\Df.xlsx" 
    ' Test to see if the file is open. 
    If IsFileOpen(fullPath) Then 
     Set dataset = Workbooks("Df.xlsx") 
    Else 
     Set dataset = Workbooks.Open(fullPath) 
    End If 

End Sub 

Function IsFileOpen(filename As String) 
    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 
+0

精彩,謝謝! – A1122