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

    • Gowrisankar
      By Gowrisankar
      Dear members of the forum,
      I need to open excel files that may or may not need a password and finally move the files that needs password to manual queue.
      Is there a fastest way to do this?
       
      PS: I have a huge respect for the rules of this forum. I am not asking assistance to override any security measure. I just need to segregate the files that needs passwords.
    • MrCheese
      By MrCheese
      Hi guys,
      without including everything (unless you want it)
      I am copying data from a table in chrome and wanting to paste it into excel.
      Copying in Chrome works.
      I can paste it into the field i want by emulating goto -> ctrl V:
      WinActivate($dataload) WinWaitActive($dataload) Sleep(500) $oWorkbook1.Sheets("ItemReturn").Activate Sleep(500) $msg = "Measuring Sheet" conwrite() ttips2() Local Const $xlUp = -4162 With $oWorkbook1.ActiveSheet ; process active sheet $oRangeLast = .UsedRange.SpecialCells($xlCellTypeLastCell) ; get a Range that contains the last used cells $iRowCount = .Range(.Cells(1, 1), .Cells($oRangeLast.Row, "B")).Rows.Count ; get the the row count for the range starting in row/column 1 and ending at the last used row/column $iLastCell = .Cells($iRowCount + 1, "B").End($xlUp).Row ; start in the row following the last used row and move up to the first used cell in column "B" and grab this row number EndWith $NewStartCell = $iLastCell + 2 $msg = "moving to location" conwrite() ttips2() Sleep(250) Send("^g") WinWait("Go To") Sleep(100) Send("B" & $NewStartCell) Sleep(100) Send("{ENTER}") Sleep(500) Send("^v")  
      But, I want to use _excel_rangecopypaste, pasting from the clipboard
      _Excel_RangeCopyPaste($oWorkbook1.ActiveSheet, default, "B" & $NewStartCell,default,$xlPasteValuesAndNumberFormats) If @error Then Exit MsgBox($MB_SYSTEMMODAL, "Excel UDF: _Excel_RangeCopy Example 2", "Error pasting cells." & @CRLF & "@error = " & @error & ", @extended = " & @extended) however, this gives me error 4 , extended@:  -2147352567
      How can i fix this or find out how to debug this error?
       
      Thanks
    • Simpel
      By Simpel
      Hi.
      I try to figure out who is using a excel workbook which I can only open "read only". I use this code:
      #include <Array.au3> #include <Excel.au3> Local $sFile = ; excel file with path on a network drive Local $oExcel = _Excel_Open(True, True) Local $oTabelle = _Excel_BookOpen($oExcel, $sFile) Local $aUsers If IsObj($oTabelle) Then $aUsers = $oTabelle.UserStatus _ArrayDisplay($aUsers) EndIf If I am the one allowed to write to the excel file (I'm the first one who opened it) then I will get an array with myself:

      If my collegue opened the excel file first and I run the code I get the following error message:
      "H:\_Conrad lokal\Downloads\AutoIt3\_COX\Tests\test.au3" (9) : ==> The requested action with this object has failed.: $aUsers = $oTabelle.UserStatus $aUsers = $oTabelle^ ERROR The excel file is on a network drive. Is that's the problem?
      Regards, Conrad
    • robertocm
      By robertocm
      change linked image paths in excel 2007 Open XML Files with AutoIt and 7-zip:
      #include <File.au3> ;Change this Local $sFind = "C:\Users\MyUserName\Documents\MyImageFolder\My%20Image1.png" Local $sReplace = "C:\Users\ANOTHERUSERNAME\Documents\AnotherImageFolder\My%20Image1.png" Local Const $sMessage = "Directory to change excel image paths" Local $sFileSelectFolder = FileSelectFolder($sMessage, "") Local $sTempDir = @ScriptDir & "\testdir" ;Required 7-zip Local $PathZipProgram = @ProgramFilesDir & "\7-Zip\" If Not(FileExists($PathZipProgram & "\7z.exe")) Then MsgBox(16, "", "7z.exe not found in path " & $PathZipProgram) Exit EndIf ;look for excel files in selected directory and all subdirectories Local $SFileList = _FileListToArrayRec($sFileSelectFolder, "*.xls.;*.xlsm", $FLTAR_FILES, $FLTAR_RECUR, $FLTAR_NOSORT, $FLTAR_FULLPATH) If Not @error Then For $i = 1 To $SFileList[0] DirRemove($sTempDir, 1) ;use x command to keep the folder stucture, -aoa Overwrite All existing files without prompt, use -r to unzip the subfolders from the zip file RunWait('"' & $PathZipProgram & '7z.exe" x -aoa -r "' & $SFileList[$i] & '" -o"' & $sTempDir & '" -y', $PathZipProgram, @SW_HIDE) __ReplaceImagePaths($sTempDir, $sFind, $sReplace) RunWait('"' & $PathZipProgram & '7z.exe" a -r "' & $SFileList[$i] & '" "' & $sTempDir & '\*" -tzip -y', $PathZipProgram, @SW_HIDE) Next Else MsgBox(16, "Error", "No files were found in the folder specified.") EndIf DirRemove($sTempDir, 1) Func __ReplaceImagePaths($sTempDir, $sFind, $sReplace) ;List all files with .xml.rels extension in the directory \xl\drawings\_rels Local $aFileList = _FileListToArray($sTempDir & "\xl\drawings\_rels", "*.xml.rels", 1, True) If @error = 1 Then ;MsgBox (0, "", "Path was invalid") SplashTextOn("Title", "Path was invalid", -1, -1, -1, -1, 1, "", 24) Sleep(2000) SplashOff() Exit EndIf If @error = 4 Then ;MsgBox (0, "No files", "No files were found") SplashTextOn("Title", "No files were found", -1, -1, -1, -1, 1, "", 24) Sleep(2000) SplashOff() Exit EndIf Local $iRetval ;Loop through the array For $i = 1 To $aFileList[0] $iRetval = _ReplaceStringInFile($aFileList[$i], $sFind, $sReplace) Next EndFunc  
      Some references:
      https://stackoverflow.com/questions/37145369/change-path-to-picture-links-in-excel http://www.jkp-ads.com/Articles/Excel2007FileFormat.asp EDITED:
      Note: it seems that if User Account Control (UAC) is enabled then 7zip is unable to overwrite the destination file (using the same name).
      In this case, a possible solution would be to rename the original excel file before (see _PathSplit in help file).
      In my case i prefer just to disable UAC
    • SOF-TECH
      By SOF-TECH
      Dear all,
      Can someone show  me how to en hance the below function to write in CSV  into column  and rows the input values ? 
      I am getting this result: 

      I would like the result to be as this 

      From A1:C1 is for headers
      From A2:C2 is for input Data
      Global Const $GUI_EVENT_CLOSE = -3 $sDataFilePath = @ScriptDir & "\Records.csv" #region ### START Koda GUI section ### Form= $Form1 = GUICreate("Demo1: New Record", 580, 115) $Input1 = GUICtrlCreateInput("", 10, 30, 270, 21) $Input2 = GUICtrlCreateInput("", 300, 30, 270, 21) $Input3 = GUICtrlCreateInput("", 10, 80, 270, 21) $Label1 = GUICtrlCreateLabel("Name:", 10, 10, 35, 17) $Label2 = GUICtrlCreateLabel("ID:", 300, 10, 18, 17) $Label3 = GUICtrlCreateLabel("Phone No:", 10, 60, 55, 17) $Button1 = GUICtrlCreateButton("Save to CSV", 450, 70, 120, 30) GUISetState(@SW_SHOW) #endregion ### END Koda GUI section ### While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 _ExportData() MsgBox(64, @ScriptName, "Record Saved.") EndSwitch WEnd Func _ExportData() If Not FileExists($sDataFilePath) Then FileWriteLine($sDataFilePath, "Name;ID;Phone No.;") EndIf For $i = $Input1 To $Input3 FileWrite($sDataFilePath, GUICtrlRead($i) & ";") Next FileWriteLine($sDataFilePath, "") EndFunc ;==>_ExportData May be Excel UDF has be to be added but I can manage that my self  
      Thank you in advance
×