[英]How to call VBA macro from AHK in Excel when editing a cell?
我有一個autohotkey腳本調用Excel宏。 基本上我有一個通用的快捷方式,可以在Excel中為我的自定義GTD應用程序添加任務
我的AHK代碼如下:
RunMSExcelMacro(MacroName, args) { ; for AHK_L
oExcel := ComObjActive("Excel.Application")
; oExcel.Workbooks("gtd_active.xlsm").Run(MacroName,args)
oExcel.Run("'gtd_active.xlsm'!"+MacroName,args)
;oExcel.Run(MacroName,args)
}
#Space::
InputBox, newTask, Add New Task to GTD, What is the new task?, , 380, 130
if (newtask = "" or ErrorLevel){ ;if blank or "cancel" pressed (ErrorLevel = 1) don't do anything
return
}
else
{RunMSExcelMacro("addFromAHK", newTask)
}
return
Excel中的方法如下:
'this script allows AutoHotKey to add items to the GTD list
'without having to even access Excel - wtf hax :-)
Sub addFromAHK(ByRef newTask As String)
Dim myCell As Range
'I don't like hardcoding this but I cant be bothered to
'make this reference the constant right now
Set myCell = MasterList.Range("C50000").End(xlUp)
'ugh such a hack. No easy way to get last cell without defiltering
Do Until IsEmpty(myCell) = True
Set myCell = myCell.Offset(1, 0)
Loop
'save the task
myCell.value = newTask
End Sub
不幸的是,如果我當前在Excel中編輯單元格,我無法調用宏,因此全局快捷方式失敗。 請注意,在我能夠調用Excel宏之前,這個失敗了。
如果我這樣做,是否有一種簡單的方法可以將AHK代碼更改為“退出單元格編輯”? 我不想寫大量的代碼來做到這一點,但我真的不確定這里的最佳方法。
我第一次使用AHK_L的try/catch
(耶!)。 看看這個代碼示例:
RunMyMacro() {
oExcel := ComObjActive("Excel.Application")
try {
oExcel.Run("'MyFile.xlsm'!TestSub")
} catch e {
ControlSend, , {Enter}, ahk_class XLMAIN
Sleep, 200
oExcel.Run("'MyFile.xlsm'!TestSub")
}
}
這是非常基本的,所以你必須自己進行微調。
如果調用宏時出錯,我們直接假設那是因為我們正在編輯一個單元格。 如果您非常細致,可以檢查異常的消息( e.Message
)以獲取錯誤代碼。 在我的機器上,消息是0x80010001 Some German BlaBla
。
要退出單元格編輯,我們只需將Enter發送到Excel窗口即可。 如果有多個Excel Windows,則必須限制窗口標題,如MyFile.xlsm ahk_class XLMAIN
。
在Sleep
(你可能想要使用確切的超時),我們再次調用我們的宏。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.