autohotkey

Open Excel sheet and press Ctrl + Q


I want to open an Excel sheet and press Ctrl+Q to call a macro. However the Ctrl+Q part is not working. What I've tried so far:

run, %A_Desktop%\test.xlsm, %A_Desktop%\
Send {Ctrl Down}{Q}{Ctrl Up}

This is not working either:

run, %A_Desktop%\test.xlsm, %A_Desktop%\
Send ^{Q}

Solution

  • Use WinWait to wait for the window to appear, WinActivate and WinWaitActive before sending any commands to it:

    ; https://autohotkey.com/docs/commands/Run.htm#RunAs
    
    ; If the script is not elevated, relaunch as administrator and kill current instance
    full_command_line := DllCall("GetCommandLine", "str")
    
    if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
    {
        try ; leads to having the script re-launching itself as administrator
        {
            if A_IsCompiled
                Run *RunAs "%A_ScriptFullPath%" /restart
            else
                Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
        }
        ExitApp
    }
    
    Run, %A_Desktop%\test.xlsm
    WinWait, test.xlsm
    WinActivate, test.xlsm
    WinWaitActive, test.xlsm
    Sleep, 300 ; if the program doesn't react immediately after activating
    Send {Ctrl Down}q{Ctrl Up}
    

    Replace test.xlsm with the exact title of the window as shown in Window Spy.