Originally Posted by
levanduyet
...In my case that I just want to check one workbook, it means that I pass the workbook name to this function only (not the full path)
To check the presence of workbook name in window text of each Excel instance the API solution can help:
' ZVI:2010-04-23 - API solution to find workbook name in text of any Excel window
Private Declare Function EnumChildWindows Lib "user32" (ByVal hWndParent As Long, ByVal lpEnumFunc As Long, ByVal lParam As Long) As Long
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
Dim hwnd As Long, IsOpen As Boolean, WbName As String
' Testing subrotine
Sub Test()
Const Wb = "Test.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)
If UCase(s) Like "MICROSOFT EXCEL *" & WbName & "*" Then
WbName = s
IsOpen = True
Exit Function
End If
EnumChildProc = 1
End Function
Replace "MICROSOFT EXCEL *" by "*" to include XLA Add-Ins project names in the search.
Vladimir