2016-04-27 275 views
1

我有一个Excel文件,说Plano.xlsx,我试图按照说明here说明使用Autohotkey上运行VBA宏脚本。 我不希望Excel在此过程中可见。 VBA代码应该在第一个表格的单元格C1中输入值99。 经过数小时的反复试验,Autohotkey脚本可以顺利运行而不会出现错误,即它会在后台打开一个Excel进程,据说编辑Excel文件时会出现 ,然后退出。问题是Excel文件根本没有改变。 VBA代码工作正常,如果我手动将它粘贴到Excel中的新VBA模块 而不使用Autohotkey。Autohotkey运行Excel VBA宏,但更改不适用

下面是代码:

#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 
} 

要获得包含在脚本请参阅here的Acc.ahk库。我的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加载项中的加载项部分 中没有任何内容被检查(我不知道这是否重要)。最后,我总是以管理员身份运行脚本。

回答

0

这可以简单地使用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 :=