检查电子表格“X.xls”是否打开?

有没有一种简单的方法来检查在VBA中当前Excel会话中是否打开了一个特别命名的电子表格?

Dim wBook As Workbook 'Check that Summary worksheet is available for update. on error goto ErrHandler Set wBook = Workbooks("CommittedSummary.xls") If wBook Is Nothing Then msgbox("Not Open") Else 'It is open MsgBox("The 'CommittedSummary.xls' workbook is already in use and cannot be updated. Please try again when the workbook Is available", _ vbCritical, "Committed Request Edit") : exit sub End If errhandler: msgbox("Workbooks is already open"):exit sub 

使用error handling如下

 Sub Working() Dim Wb As Workbook Dim strFile As String strFile = "X.xls" On Error Resume Next Set Wb = Workbooks(strFile) On Error GoTo 0 If Not Wb Is Nothing Then MsgBox strFile & " is open in this Excel instance" Else MsgBox strFile & vbNewLine & " is Closed in this Excel instance", vbCritical End If End Sub 

不要使用On Error Resume Next

只是因为代码将在该行崩溃并不意味着工作簿实际上并没有打开。 这只是意味着你的代码崩溃了。

如果您有两个Excel.Application实例,则每个实例都有一个工作簿集合。 而且可能不在正确的工作簿集合中查找。 那么你的代码会崩溃。 可能还有其他的原因,为什么你的代码崩溃。

不要在代码的正常stream程中使用错误汉德,这是不好的编程,它会导致问题。 error handling是针对无法预料的问题。