Private Declare Function GetWindowText Lib "user32" Alias "GetWindowTextA" (ByVal hwnd As Long, ByVal lpString As String, ByVal cch As Long) As Long
Private Declare Function GetWindowTextLength Lib "user32" Alias "GetWindowTextLengthA" (ByVal hwnd As Long) As Long
Declare Function EnumChildWindows Lib "user32" (ByVal hWndParent As Long, ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
Dim hwnd As Long, IsOpen As Boolean, WbName As String
' Testing subrotine
Sub Test()
Const Wb = "Book1.xls"
MsgBox "IsWorkbookOpen = " & IsWorkbookOpen(Wb) & vbLf & WbName, , Wb
End Sub
' IsFileOpen= True if WorkbookName is found in text of any Excel window
Function IsWorkbookOpen(WorkbookName As String) As Boolean
hwnd = 0: IsOpen = False: WbName = UCase(WorkbookName)
EnumChildWindows hwnd, AddressOf EnumChildProc, ByVal 0&
If IsOpen Then IsWorkbookOpen = True Else WbName = ""
End Function
' Aux function for API callback
Private Function EnumChildProc(ByVal hwnd As Long, ByVal lParam As Long) As Long
Dim s$
s = Space$(GetWindowTextLength(hwnd) + 1)
GetWindowText hwnd, s, Len(s)
s = Left$(s, Len(s) - 1)
Debug.Print s
If UCase(s) Like "*MICROSOFT EXCEL *" & WbName & "*" Then
WbName = s
IsOpen = True
Exit Function
End If
EnumChildProc = 1
End Function