1

I'm trying to check if an excel file is open, and if it is use the existing open file. If it's not, I want to open the file.

This code just gives a blank msgbox:

SetTitleMatchMode 2
xlWB := "MyExcelWorkbookTitle"

if(!WinExist(xlWB)) {
  xl := ComObjCreate("Excel.Application")
  FileSelectFile, Path
  xl.Workbooks.Open(Path)
  xl.Visible := True
  WinActivate %xlWB%
} else {
  xl := ComObjCreate("Excel.Application")
  WinActivate %xlWB%
}

rowCount := xl.ActiveSheet.UsedRange.Rows.Count - 1
MsgBox %rowCount%

What am I doing wrong here?

EDIT: To clarify, this functions correctly when no workbook is open, but when there is one already open, it just opens another one as read only.

In plain English, I want it to do this: If a workbook is open where the first x characters of the file name matches a pre-defined string, then use that workbook, otherwise open a new one.

EDIT2: I thought it would also be worth mentioning the situation I'm trying to code for. When a user first runs the script, it should open an excel workbook and update values in a web page. In the process of doing that, it may fail, and the script may exit. At that point the user is left with an open workbook with unsaved entries for the rows that the script worked through before it failed.

I want to be able to re-run the script and attach the existing open workbook to the com object so that the script can continue running as normal.

Is there a better way to do this? Should I just have the script save and close the workbook if there's an issue updating the website?

Or maybe code the script in such a way that it doesn't exit the script, but iterates the loop and tries again with the next excel row?

Jon
  • 239
  • 4
  • 15
  • 1
    [ComObjActive](http://ahkscript.org/docs/commands/ComObjActive.htm)? – wOxxOm Nov 03 '15 at 19:50
  • In which case (already open/not open/both) are you getting the problem? – MCL Nov 04 '15 at 08:38
  • when it's already open it opens another workbook as read-only rather than using the existing open workbook. when there's no workbook open it functions as intended. – Jon Nov 05 '15 at 12:34
  • @wOxxOm - I've looked at the documentation for ComObjActive, and that may be the way to do, but I'm having a hard time making sense of it...I'm pretty new to AHK. – Jon Nov 05 '15 at 12:36
  • perhaps IfWinExist would accomplish this? – Jon Nov 05 '15 at 12:46

1 Answers1

1

Better late than never. This is working for me:

SetTitleMatchMode, 2
xlWB := "xl"

if(!WinExist(xlWB)) {
    XL := ComObjCreate("Excel.Application")
    XL.Workbooks.Open( "C:\xl.xlsx" )
    XL.Visible := True

} else {
    XL := ComObjActive("Excel.Application")
    WinActivate, %xlWB%
}

ComObjActive connects you to an Excel process that is already running.

ComObjCreate starts a new Excel process.

cirus600
  • 46
  • 4