View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Michael Bednarek[_3_] Michael Bednarek[_3_] is offline
external usenet poster
 
Posts: 18
Default Testing for open workbook

On Sat, 1 Nov 2003 03:43:08 -0500, nigelab
wrote in
microsoft.public.excel.programming:

I need to create vba code within a excel macro to detemine if a
workbook is already open. If it is, I want to continue with the macro.
If it isnt, I want to open the workbook and then continue with the
macro.

I am sure this must be pretty easy. I'm just struggling to work out how
to do it.

Can anyone give me some suitable code.


Try this:
================================================== ====================
Dim wb As Workbook
Dim haveFound As Boolean
Const sName As String = "fubar.xls"

haveFound = False
For Each wb In Workbooks
If wb.Name = sName Then
haveFound = True
Exit For
End If
Next wb
MsgBox haveFound
================================================== ====================

Another common method is to simply refer to the workbook in question by
its name and use the Err object to determine the success:
================================================== ====================
On Error Resume Next
Set wb = Workbooks(sName)
If Err < 0 Then
haveFound = False
Else
haveFound = True
End If
On Error GoTo 0
MsgBox haveFound
================================================== ====================
I prefer the first method.

--
Michael Bednarek, Brisbane, Australia
http://mcmbednarek.tripod.com/ "POST NO BILLS"