Jump to content
Sign in to follow this  
andomatic

Append an excel sheet from first blank row

Recommended Posts

andomatic

Hi,

I've some data that I need to write into an existing excel sheet.The sheet has 24 active columns (a-x) and some rows populated, 30 or so. To get my data I read a locally saved htm file and populate some vars, no problem. The question is how to then find the first blank row, write my data, move to the next row, read the next data set and write it. I've got the code done for the data loop piece, just can not for the life of me figure out the excel. I don't care if I use the excel UDF or COM calls, just need a push in the right direction please... Here is what I have so far, any help is appreciated.

#include <Constants.au3>
#include <Excel.au3>
#include <Array.au3>
#include <Date.au3>
#include <File.au3>
#include <String.au3>

;WinSetState("Excel","",@SW_MINIMIZE)

Const $log = @ScriptDir & "\CreateDB.log"
Const $sSrcPath = @ScriptDir & "\result"
Const $xlPath = "\xxx\upload.xls"

Local $fTgtFile

Local $sCompName 
Local $sCompStreetAdd
Local $sCompCity 
Local $sCompState
Local $sCompZip 
Local $sCompCounrty 
Local $sCompTele

Local $sNAICS 
Local $sNAICSDesc 

Local $sSIC2
Local $sSIC4 
Local $sSICM 
Local $sSIC2Desc 
Local $sSIC4Desc 
Local $sSICMDesc 

Local $sMemberVar 
Local $sMemberTitle
Local $sMemberFunc 
Local $sMemberPosition 
Local $sMemberSIC2 
Local $sMemberSIC4 
Local $sMemberSICM 
Local $sMemberRev 
Local $sMemberEmp

_FileWriteLog($log, "***Run Start***")

Local $oExcel = _ExcelBookOpen($xlPath) ;Setup Excel
WinSetState("Excel","",@SW_MAXIMIZE)
Sleep (1000)
_ExcelSheetActivate($oExcel, "Sheet1")
Local $iRows = $oExcel.ActiveSheet.UsedRange.Rows.Count

Local $aHandle = _FileListToArray($sSrcPath, "*.htm",1)

; Work through the folder
If @error Then
    MsgBox(0, "Error", "No files matched")
Else
    ; Loop through the found files
    For $i = 1 To 5 ;$aHandle[0]
        MsgBox(4096, "File:", $aHandle[$i])
        $fTgtFile = FileOpen($sSrcPath & "\" & $aHandle[$i],0)
        If $fTgtFile = -1 Then
            MsgBox(0, "Error", "Unable to open file.")
            Exit
        EndIf

        While 1 ;MsgBox(0, "Company City:", $sCompCity[0])
            Local $line = FileReadLine($fTgtFile)
            If @error = -1 Then ExitLoop

            ;Company Name
            If StringInStr ($line,'companyName: "') Then
                $sCompName = _StringBetween($line,'companyName: "','",')
            EndIf

             ;Company Street
             If StringInStr ($line,'itemprop="streetAddress">') Then
                $sCompStreetAdd = _StringBetween($line,'itemprop="streetAddress">','</div>')
            EndIf

             ;Company City
             If StringInStr ($line,'city: "') Then
                $sCompCity = _StringBetween($line,'city: "','",')
            EndIf

             ;Company State
             If StringInStr ($line,'state: "') Then
                $sCompState = _StringBetween($line,'state: "','",')
            EndIf

             ;Company Zip
             If StringInStr ($line,'<span class="addresspostalCode" itemprop="postalCode">') Then
                $sCompZip =  _StringBetween($line,'itemprop="postalCode">','</span>')
            EndIf

            ;Company Country
             If StringInStr ($line,'"addressCountry" class="">') Then
                $sCompCountry =  _StringBetween($line,'class="">','<!--country-->')
            EndIf

            ;Company Telephone
             If StringInStr ($line,'itemprop="telephone">') Then
                $sCompTele =  _StringBetween($line,'itemprop="telephone">','</dd>')
            EndIf

            ;NACIS
             If StringInStr ($line,'naics":"') Then
                $sNAICS =  _StringBetween($line,'naics":"','"}')
            EndIf

            ;NACIS Desc
             If StringInStr ($line,'naics_desc":"') Then
                $sNAICSDesc =  _StringBetween($line,'naics_desc":"','"}')
            EndIf

            ;SIC2
            If StringInStr($line,'{"sic2":') Then
                $sSIC2 = _StringBetween($line,'{"sic2":','}')
            EndIf

            ;SIC4
            If StringInStr($line,'{"sic4":') Then
                $sSIC4 = _StringBetween($line,'{"sic4":','}')
            EndIf

            ;SIC4
            If StringInStr($line,'{"sicm":') Then
                $sSICM = _StringBetween($line,'{"sicm":','}')
            EndIf

            ;SIC2Desc
            If StringInStr($line,'{"sic2_desc":') Then
                $sSICM = _StringBetween($line,'{"sic2_desc":','}')
            EndIf

            ;SIC4Desc
            If StringInStr($line,'{"sic4_desc":') Then
                $sSICM = _StringBetween($line,'{"sic4_desc":','}')
            EndIf

            ;SICM_Desc
            If StringInStr($line,'{"sicm_desc":') Then
                $sSICM = _StringBetween($line,'{"sicm_desc":','}')
            EndIf

            ;Member Var
            If StringInStr($line,'{"member_s_var":') Then
                $sMemberVar= _StringBetween($line,'{"member_s_var":','}')
            EndIf

            ;Member Title
            If StringInStr($line,'member_attrs_title":"') Then
                $sMemberVar= _StringBetween($line,'member_attrs_title":"','}')
            EndIf

            ;Member Function
            If StringInStr($line,'{"member_function":"') Then
                $sMemberFunc= _StringBetween($line,'{"member_function":"','}')
            EndIf

            ;Member Position
            If StringInStr($line,'{"member_position":"') Then
                $sMemberPosition= _StringBetween($line,'{"member_position":"','}')
            EndIf

            ;Member SIC2
            If StringInStr($line,'{"member_sic2":"') Then
                $sMemberSIC2= _StringBetween($line,'{"member_sic2":"','}')
            EndIf

            ;Member SIC4
            If StringInStr($line,'{"member_sic4":') Then
                $sMemberSIC4= _StringBetween($line,'{"member_sic4":','}')
            EndIf

            ;Member SICM
            If StringInStr($line,'{"member_sicm":') Then
                $sMemberSICM= _StringBetween($line,'{"member_sicm":','}')
            EndIf

            ;Member Revenue
            If StringInStr($line,'{"member_revenue":"') Then
                $sMemberRev= _StringBetween($line,'{"member_revenue":','}')
            EndIf

            ;Member Employees
            If StringInStr($line,'{"member_employees":"') Then
                $sMemberRev= _StringBetween($line,'{"member_employees":','}')
            EndIf
;Stuck here on how to get those vars into excel :(


        WEnd


    Next
EndIf



Exit


; Open the workbook
;~ $oExcel = ObjCreate("Excel.Application")

;~ $oExcel = ObjCreate("Excel.Application")
;~ $oBook = $oExcel.Workbooks.Open("xxx\upload.xls")
;~ $oExcel.Visible = True
;~ $oSheet = $oBook.Worksheets(1)
;~ $oSheet.Activate
;~ $oRange = $oSheet.UsedRange
;~ $oRange.SpecialCells($xlCellTypeLastCell).Activate
;~ $newRow = $oExcel.ActiveCell.Row + 1
;~ $oExcel.Range("A" & $newRow).Activate

Share this post


Link to post
Share on other sites
andomatic

Bill,

Thanks for the link, I've incorporated the cursor move piece and it seems to work, to write in the data, I'm thinking that I need to create an array out of my info and then somehow write that across rather than down so to speak

Share this post


Link to post
Share on other sites
l3ill

If you have loops already setup its just a matter of adding the count variable (move to next cell) and adding

_ExcelWriteCell($oExcel, $i, $i, 3)

or similar..

The variables ($i) (Position to add data to excel sheet) can be controlled by a For To Next Loop.

BTW moving down is default in excel

Edited by billo

Share this post


Link to post
Share on other sites
water

You can copy it in a single statement. Use the "Usedrange" object.

This has been answered a few weeks ago. I will post the link ... as soon as I can find it ;)


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2018-06-01 - Version 1.4.9.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-01-27 - Version 1.3.3.1) - 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
water

UsedRange covers the range from the first row with data to the last row with data.

>Here you find an example using my rewrite of the Excel UDF. It's much faster than the UDF currently distributed with AutoIt.


My UDFs and Tutorials:

Spoiler

UDFs:
Active Directory (NEW 2018-06-01 - Version 1.4.9.0) - Download - General Help & Support - Example Scripts - Wiki
OutlookEX (2018-01-27 - Version 1.3.3.1) - 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

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  

  • Similar Content

    • nooneclose
      By nooneclose
      My program has to first search for names in Column D that do not match up with column C. I got that search to work using arrays. It was slow and I could not figure out how to delete them so I just manually put coded the names that do not belong. I found their cell location but I do not know how to store that location and delete it.
      This is what I have so far.
      Local $NameToDelete1[6]  = _Excel_RangeFind($OpenWorkbook, "Smith, Bill") _ArrayDisplay($NameToDelete1, "Excel UDF: _Excel_RangeFind Example 1", "", 0, "|", "Sheet|Name|Cell|Value|Formula|Comment") _Excel_RangeDelete($OpenWorkbook.ActiveSheet, $NameToDelete1[2], $xlShiftUp)  
      Please help, I wanted to have this program done yesterday but I did not see this problem until yesterday. 
    • nooneclose
      By nooneclose
      I need to perform a subtotal in excel and I would like to automate this process using Autoit if possible like always any and all help will be greatly appreciated. 
      I can not find a good example but the two from Microsoft. Here is one of the two from msdn.microsoft.com/en-us/vba/excel-vba/articles/range-subtotal-method-excel
      I do not really understand how to translate this into AutoIt, but I gave it a try and here is what I have.
      $OpenRange      = "A1:E200" $xlSum          = -4157 $Added_Array[2] = [2, 3] $OpenRange.Subtotal("B1", $xlSum, $Added_Array, True, False, True) I just need to perform a subtotal on a range based on a header called department, and then perform a sum on the results.
    • nooneclose
      By nooneclose
      How to use _Excel_RangeSort to sort my excel file by three different headers Column A1, B1, and C1 have headers on which I want to sort by. The headers on which I want to sort are department, employee type, and name.
      I still really new to AutoIt so I do not actually know how to properly start this line or lines of code, to be honest. The example code is the best I can do.
      _Excel_RangeSort($OpenWorkbook, Default, "A1:C1", "1:1", $xlDescending, Default, $xlYes, Default, $xlSortRows) I just need to sort by those three headers in that order of department, employee type, and name, plus in descending order.
       
      any and all help would be greatly appreciated.  Thank you!
    • robertocm
      By robertocm
      In the code below i can write the excel sheet with an array from an ADODB GetRows command
      But not using _Excel_RangeWrite function
      Thanks for your comments,
      #include <Array.au3> #include <Excel.au3> ;Help: COM Error Handling Global $errADODB = ObjEvent("AutoIt.Error","_ErrADODB") Local $sFilePath = @ScriptDir & "\db.mdb" Local Const $iCursorType = 0 ; adOpenForwardOnly, 3 adOpenStatic Local Const $iLockType = 3 ;1 adLockReadOnly, 3 adLockOptimistic Local Const $iOptions = 1 ; Options, 1 Evaluates as a textual definition of a command or stored procedure call ; 2 adCmdTable Global $cn = ObjCreate("ADODB.Connection") ; Create a connection object Global $rst = ObjCreate("ADODB.Recordset") ; Create a recordset object ;Global $sADOConnectionString = "Driver={Microsoft Access Driver (*.mdb)}; DBQ=" & $sFilePath ;Global $sADOConnectionString = 'DRIVER={Microsoft Access Driver (*.mdb)};Dbq=' & $sFilePath & ';uid=;pwd=MyPassword;' Global $sADOConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & $sFilePath & ";Jet OLEDB:Database Password=123" $cn.CursorLocation = 3 ; adUseClient ;https://stackoverflow.com/questions/31941487/open-adodb-connection-to-excel-file-in-read-only-mode ;https://www.w3schools.com/asp/prop_rec_mode.asp $cn.Mode = 1 ;Read-only ;$cn.CommandTimeout = 0 $cn.Open($sADOConnectionString) ; Open the connection Local $sSQL = "SELECT * FROM TABLE1" $rst.Open($sSQL, $cn, $iCursorType, $iLockType, $iOptions) ; Issue the SQL query If Not $rst.EOF = True Then Local $rstArray = $rst.GetRows() _ArrayDisplay ($rstArray) $rst.Close ;Create application object Local $oAppl = _Excel_Open() If @error Then Exit MsgBox(0, "Excel UDF: _Excel_BookOpen Example", "Error creating the Excel application object." & @CRLF & "@error = " & @error & ", @extended = " & @extended) ; Create a new workbook with only 1 worksheet Local $oWorkbook = _Excel_BookNew($oAppl, 1) If @error Then Exit MsgBox(0, "Excel UDF: _Excel_BookNew Example 1", "Error creating new workbook." & @CRLF & "@error = " & @error & ", @extended = " & @extended) ;MsgBox(0, "Excel UDF: _Excel_BookNew Example 1", "Workbook has been created successfully with only 1 worksheets.") Local $sSheet = $oWorkbook.ActiveSheet Local $aArray1D[3] = ["Field1", "Field2", "Field3"] $sSheet.Range("A1:C1").Font.Bold = True $sSheet.Range("A1:C1").value = $aArray1D Local $RecCount = UBound($rstArray) Local $TrstArray = $rstArray _ArrayTranspose($TrstArray) ;$sSheet.Range("A2:C" & $RecCount + 1).value = $TrstArray ;<<<<<<<<<<<<<< This writes the data OK ;This fails _Excel_RangeWrite($oWorkbook, Default, $TrstArray, "A2:C" & $RecCount + 1) If @error Then MsgBox(0, "Excel UDF: _Excel_RangeWrite Example 3", "Error writing to worksheet." & @CRLF & "@error = " & @error & ", @extended = " & @extended) $rst = 0 ;Release the recordset object $cn.Close ;Close the connection $cn = 0 ;Release the connection object Else $rst.Close $rst = 0 ; Release the recordset object $cn.Close ; Close the connection $cn = 0 ; Release the connection object MsgBox(262144, "", "Empty" & @CRLF & "Empty recordset" , 5) EndIf Func _ErrADODB() Msgbox(0,"ADODB COM Error","We intercepted a COM Error !" & @CRLF & @CRLF & _ "err.description is: " & @TAB & $errADODB.description & @CRLF & _ "err.windescription:" & @TAB & $errADODB.windescription & @CRLF & _ "err.number is: " & @TAB & hex($errADODB.number,8) & @CRLF & _ "err.lastdllerror is: " & @TAB & $errADODB.lastdllerror & @CRLF & _ "err.scriptline is: " & @TAB & $errADODB.scriptline & @CRLF & _ "err.source is: " & @TAB & $errADODB.source & @CRLF & _ "err.helpfile is: " & @TAB & $errADODB.helpfile & @CRLF & _ "err.helpcontext is: " & @TAB & $errADODB.helpcontext, 5) Local $err = $errADODB.number If $err = 0 Then $err = -1 $rst = 0 $cmd = 0 $cn.Close $cn = 0 Exit EndFunc  
    • Daniza
      By Daniza
      It works fine on my Excel 2007, but after I Emailed My Area Manager he told me after he Enable Macro Security nothing happen's, can someone test this to run on Excel 2016? My AM can't provide me more information 

      Thank You in Advance,
      Please see attachment.
      <snip>
×