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

时间:2013-03-18 09:51:43

标签: excel excel-vba vba

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

3 个答案:

答案 0 :(得分:2)

       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

答案 1 :(得分:2)

使用错误处理如下

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

答案 2 :(得分:-1)

请勿使用On Error Resume Next

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

如果您有两个Excel实例,则每个实例都有一个工作簿集合。也许不是在寻找合适的工作簿集合。然后你的代码就会崩溃。您的代码崩溃可能还有其他原因。

不要在代码的正常流程中使用错误处理程序,这是错误的编程,它会导致问题。错误处理是针对无法预料的问题。