Sign in to follow this  
Followers 0
ngskicker

Excel macro converted script running so slow

12 posts in this topic

#1 ·  Posted (edited)

Hi, I convert some macro functions to autoit, this script is return last cell with value supporting hidden and autofiltered not contiguous rows,

This is the original script

Option Explicit
Public Function objLast_Cell(Optional ByRef objWorksheet As Worksheet = Nothing) As Range

' --------------------------------------------------------------------------------------------------------------
' [ http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Excel/Q_28187684.html ]
'
' Question Channel: Experts Exchange > Software > Office / Productivity > Office Suites > MS Office > MS Excel
'
' ID:               28187684
' Question Title:   (Excel) reliable way to find the last row with a value,
'                   supporting hidden and autofiltered not contiguous rows
' Question Asker:   lucavilla                                 [ http://www.experts-exchange.com/M_3713400.html ]
' Question Dated:   2013-07-17 at 21:38:39
'
' Expert Comment:   fanpages                                   [ http://www.experts-exchange.com/M_258171.html ]
' Copyright:        (c) 2013 Clearlogic Concepts (UK) Limited                           [ http://NigelLee.info ]
' --------------------------------------------------------------------------------------------------------------

  Dim intColumn                                         As Integer
  Dim intLoop                                           As Integer
  Dim lngLoop                                           As Long
  Dim lngRow                                            As Long

  On Error GoTo Err_objLast_Cell

  Set objLast_Cell = Nothing

  If (objWorksheet Is Nothing) Then
     Set objWorksheet = ActiveSheet
  End If

  intColumn = objWorksheet.UsedRange.Column - 1 + objWorksheet.UsedRange.Columns.Count
  lngRow = objWorksheet.UsedRange.Row - 1& + objWorksheet.UsedRange.Rows.Count

  For lngLoop = lngRow To 1& Step -1&
      If Application.CountA(objWorksheet.Rows(lngLoop)) > 0& Then
         Exit For
      End If ' If Application.CountA(objWorksheet.Rows(lngLoop)) > 0& Then
  Next lngLoop

  lngRow = lngLoop

  For intLoop = intColumn To 1 Step -1
      If Application.CountA(objWorksheet.Columns(intLoop)) > 0 Then
         Exit For
      End If ' If Application.CountA(objWorksheet.Columns(intLoop)) > 0 Then
  Next intLoop

  intColumn = intLoop

Exit_objLast_Cell:

  On Error Resume Next

  If lngRow > 0& And _
     lngRow <= objWorksheet.Rows.Count And _
     intColumn > 0& And _
     intColumn <= objWorksheet.Columns.Count Then
     Set objLast_Cell = objWorksheet.Cells(lngRow, intColumn)
  Else
     Set objLast_Cell = Nothing
  End If ' If lngRow > 0& And lngRow <= Rows.Count And intColumn > 0& And intColumn <= Columns.Count Then

  Exit Function

Err_objLast_Cell:

  On Error Resume Next

  lngRow = 0&
  intColumn = 0

  Resume Exit_objLast_Cell

End Function

and this my converted script

#include <Excel.au3>

$fod = FileOpenDialog("Choose excel file", @ScriptDir & "", "All excel files(*.xls;*.xlsx;*.xlsm)")

Local $oX = _ExcelBookOpen($fod)
Local $oLastCell = FindLastCell($oX)

; FindLastCell return cell as object
MsgBox(0, 0, "Last cell address is: " & $oLastCell.Address)

Func FindLastCell(ByRef $oExcel)
    If Not IsObj($oExcel) Then Return SetError(1, 0, 0)
    Local $intColumn, $intLoop, $lngLoop, $lngRow, $objLast_Cell = ""

    $objWorksheet = $oExcel.ActiveSheet
    $intColumn    = $objWorksheet.UsedRange.Column - 1 + $objWorksheet.UsedRange.Columns.Count
    $lngRow       = $objWorksheet.UsedRange.Row - 1 + $objWorksheet.UsedRange.Rows.Count

    For $lngLoop = $lngRow To 1 Step -1
;~      ConsoleWrite("$lngLoop = " & $lngLoop)
        If $oExcel.Application.WorksheetFunction.CountA($objWorksheet.Rows($lngLoop)) > 0 Then ExitLoop
    Next

    $lngRow = $lngLoop

    For $intLoop = $intColumn To 1 Step -1
        If $oExcel.Application.WorksheetFunction.CountA($objWorksheet.Rows($intLoop)) > 0 Then ExitLoop
    Next

    $intColumn = $intLoop

    If $lngRow > 0 And _
        $lngRow <= $objWorksheet.Rows.Count And _
        $intColumn > 0 And _
        $intColumn <= $objWorksheet.Columns.Count Then
        $objLast_Cell = $objWorksheet.Cells($lngRow, $intColumn)
    EndIf

    Return $objLast_Cell
EndFunc 

runing macro on attached file only take a few seconds, but autoit script take more than one minute on attached script, maybe because autoit must send COM request to Excel at every loop, can someone give a workaround for this.

test.rar

Edited by ngskicker

Share this post


Link to post
Share on other sites



Maybe this saves a few cycles:

#include <Excel.au3>

$fod = FileOpenDialog("Choose excel file", @ScriptDir & "", "All excel files(*.xls;*.xlsx;*.xlsm)")

Local $oX = _ExcelBookOpen($fod)
Local $oLastCell = FindLastCell($oX)

; FindLastCell return cell as object
MsgBox(0, 0, "Last cell address is: " & $oLastCell.Address)

Func FindLastCell(ByRef $oExcel)
    If Not IsObj($oExcel) Then Return SetError(1, 0, 0)
    Local $intColumn, $intLoop, $lngLoop, $lngRow, $objLast_Cell = ""

    $objWorksheet = $oExcel.ActiveSheet
    With $objWorksheet
        $intColumn    = .UsedRange.Column - 1 + .UsedRange.Columns.Count
        $lngRow       = .UsedRange.Row    - 1 + .UsedRange.Rows.Count

        For $lngLoop = $lngRow To 1 Step -1
;~          ConsoleWrite("$lngLoop = " & $lngLoop)
            If $oExcel.Application.WorksheetFunction.CountA(.Rows($lngLoop)) > 0 Then ExitLoop
        Next

        $lngRow = $lngLoop

        For $intLoop = $intColumn To 1 Step -1
            If $oExcel.Application.WorksheetFunction.CountA(.Rows($intLoop)) > 0 Then ExitLoop
        Next

        $intColumn = $intLoop

        If $lngRow > 0 And _
            $lngRow <= .Rows.Count And _
            $intColumn > 0 And _
            $intColumn <= .Columns.Count Then
            $objLast_Cell = .Cells($lngRow, $intColumn)
        EndIf
    EndWith

    Return $objLast_Cell
EndFunc

My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

thanks, but its still need same amount of time

Share this post


Link to post
Share on other sites

The AutoIt equivalent of "On Error GoTo Err_objLast_Cell" is missing. So the VB function ends as soon as an (expected) error occurs. The AutoIt function ignores errors and hence might do unnecessary processing.

What's the goal you try to achieve?


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

This script return last cell with value supporting hidden and autofiltered not contiguous rows,

I can use

$lngRow = $oExcel.Cells.Find("*", $oExcel.Cells(1, 1), Default, Default, 1, 2).Row

to speed up the script,

but Cells.Find does not support auto filtered cell, so i can not use this,

and i do not know how to convert "On Error GoTo Err_objLast_Cell" so i just remove them

Edited by ngskicker

Share this post


Link to post
Share on other sites

Which version of Excel do you run?


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

2013, but this should run on 2010 too.

Share this post


Link to post
Share on other sites

Can't test at the moment but the SpecialCells method might return what you need. Give XlCellType xlCellTypeLastCell a try.
The enumerations can be found here.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2017-04-18 - Version 1.4.8.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (NEW 2017-02-27 - Version 1.3.1.0) - Download - General Help & Support - Example Scripts - Wiki
ExcelChart (2015-04-01 - Version 0.4.0.0) - Download - General Help & Support - Example Scripts
Excel - Example Scripts - Wiki
Word - Wiki
PowerPoint (2015-06-06 - Version 0.0.5.0) - Download - General Help & Support

Tutorials:
ADO - Wiki

 

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

I already try

$sLastCell = $oExcel.Application.Selection.SpecialCells($xlCellTypeLastCell).Address(True, True, $xlR1C1)

$sLastCell = StringRegExp($sLastCell, "\A[^0-9]*(\d+)[^0-9]*(\d+)\Z", 3)
$lngRow = $sLastCell[0]
$intColumn = $sLastCell[1]

but thats still give the same result

Edited by ngskicker

Share this post


Link to post
Share on other sites

These methods fail:
- Usedrange fails because it includes unfilled cells with only changed borders
- Find... xlFormulas method fails because it doesn't include autofiltered rows
- xlUp method is not good because it acts only on a single specified column at a time
- xlDown method is not good because it doesn't pass through intermediate unfilled cells
- xlCellTypeLastCell has some of the above limitations (eg it doesn't include autofiltered rows)
- xlCellTypeVisible count doesn't support non-contiguous visible range of rows

The CountA method works well...   however, what about optimizing those two "step -1" loops changing them to dichotomic steps? (CountA works with range of rows too, not only with single rows)

Share this post


Link to post
Share on other sites

These methods fail:

- Usedrange fails because it includes unfilled cells with only changed borders

- Find... xlFormulas method fails because it doesn't include autofiltered rows

- xlUp method is not good because it acts only on a single specified column at a time

- xlDown method is not good because it doesn't pass through intermediate unfilled cells

- xlCellTypeLastCell has some of the above limitations (eg it doesn't include autofiltered rows)

- xlCellTypeVisible count doesn't support non-contiguous visible range of rows

The CountA method works well...   however, what about optimizing those two "step -1" loops changing them to dichotomic steps? (CountA works with range of rows too, not only with single rows)

Can you giva a sample how to do that

Share this post


Link to post
Share on other sites

#12 ·  Posted (edited)

and i do not know how to convert "On Error GoTo Err_objLast_Cell" so i just remove them

I think this line can be converted to autoit code. 

You may need to include this line before your objcreate code:

Global $oErrorHandler = ObjEvent("AutoIt.Error", "_ErrFunc")

Func _ErrFunc()
;put in the code you want to convert here
EndFunc   ;==>_ErrFunc

 Between, I tested both water and your code. Both scripts are running quite fast (within 1-2sec)

Edited by soonyee91

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0

  • Similar Content

    • VeryGut
      By VeryGut
      I'm trying to insert the following formula in cell A2 using my script:
      =if(A1=""; "YES"; "NO")
      To my understanding, the line of code should be similar to this:
      _Excel_RangeWrite($MasterFile, Default, "=if(A1=""; "YES"; "NO")", "A2")
      However, it does not work, probably due to the multiple quotation marks that confuse the script :C
      How do I avoid this problem?
    • LoneWolf_2106
      By LoneWolf_2106
      Hi everybody,
      i have a question about Excel, i have to create several charts one below the other dynamically.
      I have thought to use:
       
      $oRangeLast = .UsedRange.SpecialCells($xlCellTypeLastCell) $iRowCount = .Range(.Cells(1, 1), .Cells($oRangeLast.Row, $oRangeLast.Column)).Rows.Count  
      And then to use it in this way:
      $Graph_position = "=Test1!A"&$iRowCount+2&":K"&$iRowCount+24 But it doesn't work with charts.
      Does anyone have a suggestion?
       
    • LoneWolf_2106
      By LoneWolf_2106
      Hi all,
      i have an empty csv file, i have a non formatted text file.
      What do i want to do?
      I want to automate the process "get external data" in Excel, i want to import the data from the text file and basically create a csv file with a specific character encoding.
      Is it possible with AutoIT?
       
    • breakbadsp
      By breakbadsp
      I  want to create a excel file from my script if it does not exist.
      _ExcelBookOpen throws error=2 if file does not exist, after this error i want to create new file at this point.
      can i use _FileCreate()?
      _Logger($sLogPath, "{INFO}------: Opening Excel File: " & $sExcelPath& "") While 1 Local $oExcelTestResult = _ExcelBookOpen($sExcelPath) If @error = 2 Then If not _FileCreate($sResExcelPath) Then MsgBox(0, "Error", "Error In Opening REsult Excel File: Error: " & String(@error)) _Logger($sLogPath, "{ERROR}------: Result Excel File does not exist.. tried to create new but :ERROR : " & String(@error) & "") ExitLoop Else _Logger($sLogPath, "{INFO}------: Result Excel File does not exist.. **Created New**: ") EndIf Else ExitLoop EndIf WEnd  
    • LoneWolf_2106
      By LoneWolf_2106
      Hi everybody,
      i have to store an entire row of a Excel workbook into an array.  The row index is stored in a variable.
      How can i do it?
      Thanks in advance for your support.