Seems pretty straightforward, but am not having any success.
Pretty simple, using AHK, I want to get the number of the last row in a worksheet with a value in it, going from the bottom up. I can't go top down because some rows are blank, so has to be bottom up.
My code loops through all files in a selected folder (which only contain excel files), opens them, then tries to set the print area based on how many rows are used in the file. If it's <= 43 rows, set the print area to 43rd row, if it's more, set the print area to that row.
My code for test.ahk
looks like this:
FileSelectFolder, WhichFolder ; Ask the user to pick a folder.
Loop, %WhichFolder%\*.*
{
Xl := ComObjActive("Excel.Application")
Xl.Workbooks.open(A_LoopFileFullPath) ; open workbook
Xl.Visible := 1 ; make Excel Application visible
Xl.DisplayAlerts := False
; First check if it's the dumb file that opens first, not part of the folder
if xl.ActiveWorkbook.Name = "test.ahk" {
xl.Quit()
continue
}
; Wait for the workbook to open
Sleep, 2000
; Always start on the first worksheet
Xl.Worksheets(1).Activate
; Now find the last used row for the print area
; If the last used row is on page 1, set it to the 43rd row
lastRow := xl.ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
;MsgBox, %lastRow%
; Set the print area
if lastRow <= 43 {
xl.ActiveSheet.PageSetup.PrintArea := "A1:K43"
else {
xl.ActiveSheet.PageSetup.PrintArea := "A1:K"lastRow
}
; Wait to close the script if you want for testing
Sleep, 20000
; Close and save the workbook
xl.ActiveWorkbook.Close(1)
Xl.DisplayAlerts := True
}
ExitApp
...and I'm getting this error:
I've tried lots of other combinations of trying to get the last row with a value in it too, but have had no success. Any help would be greatly appreciated. Thanks.