Autohotkey 运行 Excel VBA 宏但未应用更改

Autohotkey runs Excel VBA macro but changes are not applied

我有一个 Excel 文件,比如说 Plano.xlsx,我正在尝试 运行 一个 VBA 宏脚本,按照 [=18] 所述的说明使用 Autohotkey =]. 我不希望 Excel 在此过程中可见。 VBA 代码应该在第一个 sheet 的单元格 C1 中输入值 99。 经过数小时的反复试验,Autohotkey 脚本 运行 顺利无误,即据称它在后台打开了一个 Excel 进程 编辑 Excel 文件然后退出。问题是 Excel 文件根本没有改变。 VBA 代码如果我手动粘贴就可以正常工作 在 Excel 的新 VBA 模块中,不使用 Autohotkey。

代码如下:

#SingleInstance force

#Include Acc.ahk

VBcode=
(
Sub myFunction()
    Worksheets(1).Select
    Worksheets(1).Range("C1").Select
    Selection.Value = 99
End Sub
)

Excel_Run("myFunction")

Excel_Run(sFunction){
    FilePath = C:\Users\KostasK\Desktop\Plano.xlsx
    oExcel := ComObjCreate("Excel.Application")
    Excel_ImportCode(VBcode)
    oWorkbook := oExcel.Workbooks.Open(FilePath)
    Excel_Get().Run(sFunction)
    oWorkbook.Save
    oExcel.Quit
}

Excel_ImportCode(VBcode){
    if fileexist(A_ScriptDir . "\tempvbcode.txt")
        FileDelete, %A_ScriptDir%\tempvbcode.txt

    FileAppend, %VBcode%, %A_ScriptDir%\tempvbcode.txt

    Excel_Get().ActiveWorkbook.VBProject
        .VBComponents.Import(A_ScriptDir . "\tempvbcode.txt")
}

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

要获取脚本中包含的 Acc.ahk 库,请参阅 here。我的 Autohotkey 版本是 v.1.1.23.05,我使用 Excel 2013。我没有 仔细查看 Excel_Get() 函数,但我使用它而不是 ComObjActive("Excel.Application"),因为后者会产生错误。那里 是关于 here 的一些有用信息。最后请注意,我在 Excel 信任中心启用了以下选项: Enable all macros (not recommended, potentially dangerous code can run)Trust access to the VBA project object model。此外,在加载项部分 在 COM 加载项中,没有检查任何内容(我不知道这是否重要)。最后,我总是运行脚本管理员。

无需 VBA 宏即可轻松完成此操作,同时关闭文件。

FilePath = C:\Users\KostasK\Desktop\Plano.xlsx
oExcel := ComObjGet(FilePath)
oExcel.Worksheets("Sheet1").Range("C1").VALUE := "99" ; you can put actual sheet name instead "sheet1"
oExcel.Save
oExcel.Quit
oExcel :=