Option Explicit
Private Declare Function FindWindowEx Lib "User32" Alias "FindWindowExA" (ByVal hWnd1 As Long, ByVal hWnd2 As Long, ByVal lpsz1 As String, ByVal lpsz2 As String) As Long
Private Declare Function IIDFromString Lib "ole32" (ByVal lpsz As Long, ByRef lpiid As GUID) As Long
Private Declare Function AccessibleObjectFromWindow Lib "oleacc" (ByVal hWnd As Long, ByVal dwId As Long, ByRef riid As GUID, ByRef ppvObject As Object) As Long
Private Type GUID: Data1 As Long: Data2 As Integer: Data3 As Integer: Data4(7) As Byte: End Type
Private Const RETURN_OK As Long = &H0
Private Const IID_IDispatch As String = "{00020400-0000-0000-C000-000000000046}"
Private Const OBJID_NATIVEOM As Long = &HFFFFFFF0
'*******************************************************************************************
'un exemple ici EN ANGLAIS de l'utilisation de l'api AccessibleObjectFromWindow
'lien:https://social.msdn.microsoft.com/Forums/office/en-US/e3e99712-01a7-483e-bf0e-52bb1f94889c/how-to-use-accessibleobjectfromwindow-api-in-vba-to-get-excel-application-object-from-excel?forum=exceldev
'*******************************************************************************************
Function GetAllInstanceExceL()
Dim x, hWinDesk&, hWin7&, hWndXL&, Tablexcel() As Object, oWB As Object, oWS As Object, obj As Object, iID As GUID, oXLApp As Object
hWndXL = FindWindowEx(0&, 0&, "XLMAIN", vbNullString) 'trouve le premier handle excel
Do While hWndXL > 0 'boucle jusqu'a que ""hWndXL"" retourne "0"!!
x = x + 1 '// Incrementation de la variable x
hWinDesk = FindWindowEx(hWndXL, 0&, "XLDESK", vbNullString) 'on descend d'un enfant de "XLMAIN"
hWin7 = FindWindowEx(hWinDesk, 0&, "EXCEL7", vbNullString) 'on descend au petit fils de "XLMAIN"
'Debug.Print "Instance #" & x & ": "; "Handle: " & hWndXL '/juste Pour control provisoire affichage dans la fenetre d'execution
Call IIDFromString(StrPtr(IID_IDispatch), iID) 'construction de "IID" avec le clisd(IID_IDispatch)pour lecture des propriété de la fenetre correspondant au handle
If AccessibleObjectFromWindow(hWin7, OBJID_NATIVEOM, iID, obj) = RETURN_OK Then ReDim Preserve Tablexcel(1 To x): Set Tablexcel(x) = obj.Application ' test dispo d'assecibilité de la fenetre :"obj" retourne un object
hWndXL = FindWindowEx(0, hWndXL, "XLMAIN", vbNullString)
'un exemple ici en francais de l'api AccessibleObjectFromWindow :https://social.msdn.microsoft.com/Forums/office/en-US/e3e99712-01a7-483e-bf0e-52bb1f94889c/how-to-use-accessibleobjectfromwindow-api-in-vba-to-get-excel-application-object-from-excel?forum=exceldev
Loop
GetAllInstanceExceL = Tablexcel
End Function
Sub test()
Dim instances, wb As Workbook, i
instances = GetAllInstanceExceL
For i = 1 To UBound(instances)
For Each wb In instances(i).Workbooks
Debug.Print "instance : " & i & " " & wb.Name
'l'object instances(i) et son ".wb" peuvent être exploité de toute les manières identiquement à des object instanciés ou nommés en dur dans le code
Next
Next
End Sub