Excel_Get - Connect to active Excel Window

Post your working scripts, libraries and tools.
AHK_user
Posts: 515
Joined: 04 Dec 2015, 14:52
Location: Belgium

Excel_Get - Connect to active Excel Window

Post by AHK_user » 13 Aug 2022, 07:44

Here is some usefull code to connect to the active Excel window.

(this uses functions from viewtopic.php?f=83&t=93790&hilit=acc)

Code: Select all

#Requires AutoHotKey v2.0-beta.3
#SingleInstance force

oExcel := Excel_Get()
oWorkBook := oExcel.ActiveWorkbook
oSheet := oExcel.ActiveWorkbook.ActiveSheet
SArr := oSheet.Range("A1:CI200").value
Msgbox(SArr[2, 2])
return

Excel_Get(WinTitle := "ahk_class XLMAIN") {	; by Sean and Jethrow, minor modification by Learning one
    hwnd := ControlGethwnd("Excel71", WinTitle)
    if !hwnd
        return
    Window := Acc_ObjectFromWindow(hwnd, -16)
    Loop
        try
            oExcel := Window.Application
        catch
            ControlSend("{esc}", "Excel71", WinTitle)
    Until !!oExcel
    return oExcel
}


Acc_ObjectFromWindow(hWnd, idObject := -4) {	; OBJID_WINDOW:=0, OBJID_CLIENT:=-4
    Acc_Init()
    capIID := 16
    bIID := Buffer(capIID)
    idObject &= 0xFFFFFFFF
    numberA := idObject == 0xFFFFFFF0 ? 0x0000000000020400 : 0x11CF3C3D618736E0
    numberB := idObject == 0xFFFFFFF0 ? 0x46000000000000C0 : 0x719B3800AA000C81
    addrPostIID := NumPut("Int64", numberA, bIID)
    addrPPIID := NumPut("Int64", numberB, addrPostIID)
    gotObject := DllCall("oleacc\AccessibleObjectFromWindow"
        , "Ptr", hWnd
        , "UInt", idObject
        , "Ptr", -capIID + addrPPIID
        , "Ptr*", &pacc := 0
    )
    if (gotObject = 0) {
        return ComObjFromPtr(pacc)
    }
}

Acc_Init() {
    static h := 0
    If Not h {
        h := DllCall("LoadLibrary", "Str", "oleacc", "Ptr")
    }
}

Return to “Scripts and Functions (v2)”