Is there a simple way to check whether a particularly-named spreadsheet is open in the current Excel session, from VBA?
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
Use error handling as below
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
Just because the code will crashes at that line doesn’t mean the workbook is not actually open. It just means your code crashed.
If you have two instances of Excel.Application each instance with have a workbooks collection. And might not be looking in the right workbooks collection. Then your code will crash. There could be other reasons why your code crashes.
Don’t use Error handers in the normal flow of your code it’s bad programming and it’ll lead to problems. Error handling is for problems that are unforeseen.