
While using AutoHotkey to connect to Excel is “easy”, it is also easy to be trying to use call a function to the wrong Excel object. In this video we discuss the below diagram and explain how to use AutoHotkey and Excel Object model.

Here is the function for specifying which Excel object you want to connect to
;1=Application 2=Workbook 3=Worksheet
XL_Handle(XL_Applic,1) ;Application
XL_Handle(XL_workbook,2) ;Workbook
XL_Handle(XL_Worksheet,3) ;Worksheet
MsgBox % XL_Applic.name "`r"
. XL_workbook.name "`r"
. XL_Worksheet.name
XL_Handle(ByRef PXL,Sel){
ControlGet, hwnd, hwnd, , Excel71, ahk_class XLMAIN ;identify the hwnd for Excel
IfEqual,Sel,1, Return, PXL:= ObjectFromWindow(hwnd,-16).application ;Handle to Excel Application
IfEqual,Sel,2, Return, PXL:= ObjectFromWindow(hwnd,-16).parent ;Handlle to active Workbook
IfEqual,Sel,3, Return, PXL:= ObjectFromWindow(hwnd,-16).activesheet ;Handle to Active Worksheet
}
;***********adapted from ACC.ahk*******************
ObjectFromWindow(hWnd, idObject = -4){
(if Not h)?h:=DllCall("LoadLibrary","Str","oleacc","Ptr")
If DllCall("oleacc\AccessibleObjectFromWindow","Ptr",hWnd,"UInt",idObject&=0xFFFFFFFF,"Ptr",-VarSetCapacity(IID,16)+NumPut(idObject==0xFFFFFFF0?0x46000000000000C0:0x719B3800AA000C81,NumPut(idObject==0xFFFFFFF0?0x0000000000020400:0x11CF3C3D618736E0,IID,"Int64"),"Int64"), "Ptr*", pacc)=0
Return ComObjEnwrap(9,pacc,1)
}
return


