AutoHotkey's ComObjActive handle to specific W

2019-04-17 06:26发布

问题:

The simplest way to create a handle to your currently active Excel sheets in your .ahk script is:

Xl := ComObjActive("Excel.Application")

Nonetheless, if one switches to another workbook, this becomes the new "currently active sheet" and AutoHotkey tries to use methods for sheets and cells on the new workbook through COM: of course scripts designed to work with specific sheets and cells don't work anymore on a different workbook.

Do you know how to create COM handles to specific workbooks instead of currently active sheet?

The goal should be to allow the user to loop between workbooks without Xl object losing its previous handle and going to a new one.

Example

Open an Excel workbook from scratch and type 1234 in cell A1 of sheet named "Sheet1"; then create a new .ahk script with the following content:

#Persistent

Xl := ComObjActive("Excel.Application")
SetTimer, xlRead, 5000
Return

xlRead:
{
  value := Xl.Sheets("Sheets1").Range("A1").Value
  MsgBox, %value%
}
Return

Script above should display "1234" in a message box every 5 seconds.

While that is running, open a new workbook and type 5678 in cell A1 of sheet named "Sheet1" and wait for 5 seconds: according to my trials, AutoHotkey should just switch the handle to the new active sheet and show a message box whose content is "5678".

Any way to keep it linked to the first sheet? Of course assume one can save Excel files to hard disk with proper names which COM can refer to.

回答1:

one way is to store the active workbook object in a variable like this

#Persistent

oExcel := ComObjActive("Excel.Application")
this_book := oExcel.ActiveWorkbook
SetTimer, xlRead, 10000
Return

xlRead:
{
  value := this_book.Sheets(1).Range("A1").Value
  MsgBox, %value%
}
Return

2nd way is to use ComObjGet with the full name of the active workbook if you know it before hand no need for the ControlGetText command just use the workbooks full name

#Persistent
SetTitleMatchMode, 2

ControlGetText, WorkBookName, Excel71, Microsoft Excel
oWorkbook := ComObjGet(WorkBookName)

SetTimer, xlRead, 10000
Return

xlRead:
{
  value := oWorkbook.Sheets(1).Range("A1").Value
  MsgBox, %value%
}
Return

You can also use ComObjGet with the full path of an excel file it will return the workbook object

#Persistent
fileselectfile, path

oWorkbook := ComObjGet(path)
SetTimer, xlRead, 10000
Return

xlRead:
{
  value := oWorkbook.Sheets(1).Range("A1").Value
  MsgBox, %value%
}
Return

Hope this helps you do what you need