Search the Community
Showing results for tags 'ARRAY'.
-
I've just written a small script that compares two strings and returns the similarity of those two in %. I know of StringCompare, but I want to get a percentage and I also want to get in touch with Autoit. Compiling doesn't cause any problems, but actually running it does. In line 20 it has a problem with the index and says "Subscript used on non-accessible variable". What's causing that problem, and how can I solve it? Thanks! And sorry for my ugly style Similarity.au3
- 7 replies
-
- string
- comparison
-
(and 2 more)
Tagged with:
-
_GetDuplicates.au3 Returns an array of duplicate values in a 2D or 1D array. on the occasion of the post ; https://www.autoitscript.com/forum/topic/211972-get-the-duplicates-value-of-array/ ;---------------------------------------------------------------------------------------- ; Title...........: _GetDuplicates.au3 ; Description.....: Returns an array of duplicate values in a 2D or 1D array. ; AutoIt Version..: 3.3.16.1 Author: ioa747 ; Note............: Testet in Win10 22H2 ;---------------------------------------------------------------------------------------- #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7 #include <Array.au3> #include <File.au3> #include <FileConstants.au3> ;~ Global $aFilms[] = ["Rambo", "Rambo II", "Rambo III", "Rocky", "Rocky II", "Rocky III", "Rocky IV", "Possessed", "Edge of Tomorrow", "The Ghost Writer", "rocky ii", "RAMBO iii"] ;~ $aDuplicates = _GetDuplicates($aFilms) ;~ _ArrayDisplay($aDuplicates, "$aDuplicates") ; Display the unique array. ;~ Exit ; Find all Duplicates song from the "D:\Music\Bob Marley" folder Global $aFileInfo = _PropertiesListToArray("D:\Music\Bob Marley", "*.mp3;*.wma", "20, 14, 26, 21, 16, 28", 1) _ArrayDisplay($aFileInfo, "$aFileInfo") Global $aDuplicates = _GetDuplicates($aFileInfo, 4) _ArrayDisplay($aDuplicates, "$aDuplicates") ; Display the unique array. ConsoleWrite("Report Duplicates =============================" & @CRLF) Global $aDbl ConsoleWrite("Duplicates count: " & $aDuplicates[0] & @CRLF) For $i = 1 To $aDuplicates[0] $aDbl = StringSplit($aDuplicates[$i], ";") ConsoleWrite($i & ") " & $aFileInfo[$aDbl[1]][4]) ConsoleWrite(" - " & $aDbl[0] & " file(s)" & @CRLF) For $z = 1 To $aDbl[0] ConsoleWrite(@TAB & "found in " & $aFileInfo[$aDbl[$z]][0] & @CRLF) Next Next ; #FUNCTION# -------------------------------------------------------------------------------------------------------------------- ; Name...........: _PropertiesListToArray() ; Description ...: Lists files from specified path with Ext properties ; Syntax.........: _PropertiesListToArray($sFolderPath [, $sMask = "*" [, $sGetDetailsOf = "1, 2, 3, 4, 6" [, $iRecur = 0]]) ; Parameters ....: $sFolderPath - Initial path used to generate filelist. ; : $sMask - [optional] Filter for result. Multiple filters must be separated by ";" ; : $sGetDetailsOf - [optional] The Column of properties to return ; : $iRecur - [optional] 0=Do not search in subfolders ,1=Search in all subfolders ; Return value...: 2D Array ; Author ........: ioa747 ; Notes .........: ;-------------------------------------------------------------------------------------------------------------------------------- Func _PropertiesListToArray($sFolderPath, $sMask = "*", $sGetDetailsOf = "1, 2, 3, 4, 6", $iRecur = 0) Local $hTimer = TimerInit() Local $oShell = ObjCreate("Shell.Application") Local $oDir = $oShell.Namespace($sFolderPath) ConsoleWrite("$sFolderPath=" & $sFolderPath & @CRLF) Local $aFiles = _FileListToArrayRec($sFolderPath, $sMask, $FLTAR_FILES, $iRecur, $FLTAR_FASTSORT, $FLTAR_FULLPATH) If @error Then Local $sError = "Path not found or invalid;Invalid Include parameter;Invalid Exclude parameter;" $sError &= "Invalid Exclude_Folders parameter;Invalid $iReturn parameter;Invalid $iRecur parameter;" $sError &= "Invalid $iSort parameter;Invalid $iReturnPath parameter;No files/folders found" Local $aErr = StringSplit($sError, ";", 2) ToolTip($aErr[@extended] & @CRLF & " ", @DesktopWidth / 4, @DesktopHeight / 2, "Error:", 2) Sleep(4000) ToolTip("") Return SetError(1, @extended, "") EndIf Local $aColumns = StringSplit($sGetDetailsOf, ", ", 1) Local $aData[$aFiles[0] + 1][1] For $i = 1 To $aColumns[0] _ArrayColInsert($aData, $i) $aData[0][$i] = $oDir.GetDetailsOf($oDir.Items, $aColumns[$i]) Next $aData[0][0] = UBound($aData) - 1 Local $sDir, $sFileName, $oFile Local $iUnitCnt = 100 / $aFiles[0] ProgressOn("Progress...", "Search for " & $sMask & " files", "0%") For $i = 1 To $aFiles[0] $sDir = StringLeft($aFiles[$i], StringInStr($aFiles[$i], "\", 0, -1)) $sFileName = StringMid($aFiles[$i], StringInStr($aFiles[$i], "\", 0, -1) + 1) $aData[$i][0] = $aFiles[$i] $oDir = $oShell.NameSpace($sDir) $oFile = $oDir.Parsename($sFileName) For $c = 1 To $aColumns[0] $aData[$i][$c] = $oDir.GetDetailsOf($oFile, $aColumns[$c]) Next ProgressSet($i * $iUnitCnt, Round($i * $iUnitCnt, 0) & "%") Next ProgressSet(100, "Done", "Complete") ProgressOff() ConsoleWrite($aFiles[0] & " files processed in: " & Round(TimerDiff($hTimer) / 1000, 3) & " seconds " & @LF) Return $aData EndFunc ;==>_PropertiesListToArray ; #FUNCTION# -------------------------------------------------------------------------------------------------------------------- ; Name...........: _GetDuplicates ; Description....: Returns an array of duplicate values in a 2D or 1D array. ; Syntax.........: _GetDuplicates($aArray, $iColumn = 0) ; Parameters.....: $aArray - The input array. ; $iColumn - [Optional] The column index to check for duplicates (default is 0). ; Return values..: An array of duplicate values. ; Author ........: ioa747 ; Notes .........: This function assumes that the input array is a 2D or 1D array. ;-------------------------------------------------------------------------------------------------------------------------------- Func _GetDuplicates(ByRef $aArray, $iColumn = 0) Local $sStrIndex, $iDuplCnt Local $aDuplicates[] = [0] Local $aIndex[UBound($aArray)] For $i = 0 To UBound($aArray) - 1 If $aIndex[$i] = "Duplicates" Then ContinueLoop $sStrIndex = "" $iDuplCnt = 0 For $d = 0 To UBound($aIndex) - 1 Local $iColCnt = UBound($aArray, 2) ;ConsoleWrite("$iColCnt=" & $iColCnt & @CRLF) If $iColCnt > 0 Then ; if $aArray = 2D If $aArray[$i][$iColumn] = $aArray[$d][$iColumn] Then $sStrIndex &= $d & ";" $iDuplCnt += 1 If $iDuplCnt > 1 Then $aIndex[$d] = "Duplicates" EndIf Else ; if $aArray = 1D If $aArray[$i] = $aArray[$d] Then $sStrIndex &= $d & ";" $iDuplCnt += 1 If $iDuplCnt > 1 Then $aIndex[$d] = "Duplicates" EndIf EndIf Next $sStrIndex = StringTrimRight($sStrIndex, 1) ;ConsoleWrite("$sStrIndex=" & $sStrIndex & @CRLF) $aIndex[$i] = $sStrIndex Local $asplit = StringSplit($sStrIndex, ";") If $asplit[0] > 1 Then ReDim $aDuplicates[UBound($aDuplicates) + 1] $aDuplicates[0] += 1 $aDuplicates[$aDuplicates[0]] = $sStrIndex EndIf Next Return $aDuplicates EndFunc ;==>_GetDuplicates #cs $sGetDetailsOf - The Column of properties to return [0] = Name [1] = Size [2] = Item type [3] = Date modified [4] = Date created [5] = Date accessed [6] = Attributes [7] = Offline status [8] = Availability [9] = Perceived type [10] = Owner [11] = Kind [12] = Date taken [13] = Contributing artists [14] = Album [15] = Year [16] = Genre [17] = Conductors [18] = Tags [19] = Rating [20] = Authors [21] = Title [22] = Subject [23] = Categories [24] = Comments [25] = Copyright [26] = # [27] = Length [28] = Bit rate [29] = Protected [30] = Camera model [31] = Dimensions [32] = Camera maker [33] = Company [34] = File description [35] = Masters keywords [36] = Masters keywords [42] = Program name [43] = Duration [44] = Is online [45] = Is recurring [46] = Location [47] = Optional attendee addresses [48] = Optional attendees [49] = Organizer address [50] = Organizer name [51] = Reminder time [52] = Required attendee addresses [53] = Required attendees [54] = Resources [55] = Meeting status [56] = Free/busy status [57] = Total size [58] = Account name [60] = Task status [61] = Computer [62] = Anniversary [63] = Assistant's name [64] = Assistant's phone [65] = Birthday [66] = Business address [67] = Business city [68] = Business country/region [69] = Business P.O. box [70] = Business postal code [71] = Business state or province [72] = Business street [73] = Business fax [74] = Business home page [75] = Business phone [76] = Callback number [77] = Car phone [78] = Children [79] = Company main phone [80] = Department [81] = E-mail address [82] = E-mail2 [83] = E-mail3 [84] = E-mail list [85] = E-mail display name [86] = File as [87] = First name [88] = Full name [89] = Gender [90] = Given name [91] = Hobbies [92] = Home address [93] = Home city [94] = Home country/region [95] = Home P.O. box [96] = Home postal code [97] = Home state or province [98] = Home street [99] = Home fax [100] = Home phone [101] = IM addresses [102] = Initials [103] = Job title [104] = Label [105] = Last name [106] = Mailing address [107] = Middle name [108] = Cell phone [109] = Nickname [110] = Office location [111] = Other address [112] = Other city [113] = Other country/region [114] = Other P.O. box [115] = Other postal code [116] = Other state or province [117] = Other street [118] = Pager [119] = Personal title [120] = City [121] = Country/region [122] = P.O. box [123] = Postal code [124] = State or province [125] = Street [126] = Primary e-mail [127] = Primary phone [128] = Profession [129] = Spouse/Partner [130] = Suffix [131] = TTY/TTD phone [132] = Telex [133] = Webpage [134] = Content status [135] = Content type [136] = Date acquired [137] = Date archived [138] = Date completed [139] = Device category [140] = Connected [141] = Discovery method [142] = Friendly name [143] = Local computer [144] = Manufacturer [145] = Model [146] = Paired [147] = Classification [148] = Status [149] = Status [150] = Client ID [151] = Contributors [152] = Content created [153] = Last printed [154] = Date last saved [155] = Division [156] = Document ID [157] = Pages [158] = Slides [159] = Total editing time [160] = Word count [161] = Due date [162] = End date [163] = File count [164] = File extension [165] = Filename [166] = File version [167] = Flag color [168] = Flag status [169] = Space free [172] = Group [173] = Sharing type [174] = Bit depth [175] = Horizontal resolution [176] = Width [177] = Vertical resolution [178] = Height [179] = Importance [180] = Is attachment [181] = Is deleted [182] = Encryption status [183] = Has flag [184] = Is completed [185] = Incomplete [186] = Read status [187] = Shared [188] = Creators [189] = Date [190] = Folder name [191] = Folder path [192] = Folder [193] = Participants [194] = Path [195] = By location [196] = Type [197] = Contact names [198] = Entry type [199] = Language [200] = Date visited [201] = Description [202] = Link status [203] = Link target [204] = URL [208] = Media created [209] = Date released [210] = Encoded by [211] = Episode number [212] = Producers [213] = Publisher [214] = Season number [215] = Subtitle [216] = User web URL [217] = Writers [219] = Attachments [220] = Bcc addresses [221] = Bcc [222] = Cc addresses [223] = Cc [224] = Conversation ID [225] = Date received [226] = Date sent [227] = From addresses [228] = From [229] = Has attachments [230] = Sender address [231] = Sender name [232] = Store [233] = To addresses [234] = To do title [235] = To [236] = Mileage [237] = Album artist [238] = Sort album artist [239] = Album ID [240] = Sort album [241] = Sort contributing artists [242] = Beats-per-minute [243] = Composers [244] = Sort composer [245] = Disc [246] = Initial key [247] = Part of a compilation [248] = Mood [249] = Part of set [250] = Period [251] = Color [252] = Parental rating [253] = Parental rating reason [254] = Space used [255] = EXIF version [256] = Event [257] = Exposure bias [258] = Exposure program [259] = Exposure time [260] = F-stop [261] = Flash mode [262] = Focal length [263] = 35mm focal length [264] = ISO speed [265] = Lens maker [266] = Lens model [267] = Light source [268] = Max aperture [269] = Metering mode [270] = Orientation [271] = People [272] = Program mode [273] = Saturation [274] = Subject distance [275] = White balance [276] = Priority [277] = Project [278] = Channel number [279] = Episode name [280] = Closed captioning [281] = Rerun [282] = SAP [283] = Broadcast date [284] = Program description [285] = Recording time [286] = Station call sign [287] = Station name [288] = Summary [289] = Snippets [290] = Auto summary [291] = Relevance [292] = File ownership [293] = Sensitivity [294] = Shared with [295] = Sharing status [297] = Product name [298] = Product version [299] = Support link [300] = Source [301] = Start date [302] = Sharing [303] = Availability status [304] = Status [305] = Billing information [306] = Complete [307] = Task owner [308] = Sort title [309] = Total file size [310] = Legal trademarks [311] = Video compression [312] = Directors [313] = Data rate [314] = Frame height [315] = Frame rate [316] = Frame width [317] = Spherical [318] = Stereo [319] = Video orientation [320] = Total bitrate [321] = CMYK Profile [322] = Primary color mode [323] = Colors [324] = Effects [325] = External bitmaps [326] = Fills [327] = Fonts used [328] = Fonts embedded [329] = Grayscale Profile [330] = Languages [331] = Layer names [332] = Object count [333] = Object names [334] = Objects [335] = Outlines [336] = Page names [337] = Paper orientation [338] = Paper size [339] = Color palettes [340] = Rendering intent [341] = RGB Profile [342] = Spot colors [343] = Styles [344] = Bitmap compression [345] = Compression ratio [346] = Graphic compression [347] = Color mode [348] = Color Profile [349] = Audio tracks [350] = Bit depth [351] = Contains chapters [352] = Content compression [353] = Subtitles [354] = Subtitle tracks [355] = Video tracks #CE $sGetDetailsOf - The Column of properties to return Please, every comment is appreciated! leave your comments and experiences here! Thank you very much
-
This script allows you to 'browse' an array and view it's content. It's similar to the _ArrayDisplay() command, but this one has no limit on the number of dimensions. Nested array (array of arrays) are also allowed. (I'm been inspired by this @JohnOne's Post) Since multidimensional arrays can be considered as many bidimensional arrays grouped toghether, with this script you can view any of the many 2d arrays by selecting the dimension (the sheet number) you want to see through the ComboBoxes located at the top of the viewed sheet. regarding the arrays of array, if are present, those are listed on the treeview on the left side, where you can see their locations within the tree, and easily selected to be as well browsed by a click. I'm aware that there is a wide margin of aesthetic improvement, anyway the basic functionality works quite well. I hope it can be usefull ; Func _ArrayView() ; Will display content of arrays of any dimension, and even nested arrays if any ; #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <GuiListView.au3> #include <GUITreeView.au3> #include <GUIScrollBars.au3> #include <ScrollBarConstants.au3> #include <ComboConstants.au3> #include <GuiStatusBar.au3> ; -- build an example array (somewhat chaotic.. just to show something) -- ; 4D array (main array) Local $aA[10][5][6][3] For $d1 = 0 To 9 For $d2 = 0 To 4 For $d3 = 0 To 5 For $d4 = 0 To 2 $aA[$d1][$d2][$d3][$d4] = $d1 & "." & $d2 & "." & $d3 & "." & $d4 Next Next Next Next ; some 1D arrays with multi nested arrays Local $aMonths1 = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] Local $aMonths2 = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember", $aMonths1] Local $aMonths3 = ["Sijecanj", "veljaca", "ožujka", "travanj", "Svibanj", "lipanj", "srpanj", "kolovoz", "rujan", "listopad", "studeni", "prosinac", $aMonths2] Local $aMonths4 = ["Janvier", "Février", "Mars", "Avril", "mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre", $aMonths3] Local $aMonths5 = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'giu', 'Luglio', 'Agosto', 'Settembre', 'ottobre', 'Novembre', 'Dicembre', $aMonths4] Local $aMonths = ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember", $aMonths5] ; a simple 2D array Local $aWeekdays = [['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'], _ ['Lunedì', 'martedì', 'mercoledì', 'giovedì', 'venerdì', 'sabato', 'domenica'], _ ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'], _ ['Måndag', 'tisdag', 'onsdag', 'torsdag', 'fredag', 'lördag', 'söndag'], _ ['PoniedziaÅ‚ek', 'Wtorek', 'Åšroda', 'Czwartek', 'PiÄ…tek', 'Sobota', 'Niedziela'], _ ['Montag', 'Dienstag', 'Mittwoch', 'Donnerstag', 'Freitag', 'Samstag', 'Sonntag']] ; array $aMonths goes in cell [5][3] dimension [0][0] of main array $aA[5][3][0][0] = $aMonths ; array $aWeekdays goes in cell [6][3] dimension [0][0] of main array $aA[6][3][0][0] = $aWeekdays $aWeekdays[1][1] = $aWeekdays ; self nest $aWeekdays in cell [1][1] $aA[9][4][0][1] = $aWeekdays ; new $aWeekdays goes in cel [9][4] dimension [0][1] of main array _ArrayView($aA) ; show main array ; #FUNCTION# ==================================================================================================================== ; Name ..........: _ArrayView ; Description ...: Allows to view content of amono or multidimensional array. Array of arrays are also allowed ; Syntax ........: _ArrayView(Byref $_aInput) ; Parameters ....: $_aInput - The array that you want to 'Browse' ; Return values .: on success returns 1 ; on faillure returns 0 and set @Error to 1 (passed argument is not an array) ; Author ........: @Chimp ; Modified ......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: ; =============================================================================================================================== Func _ArrayView(ByRef $_aInput) If Not IsArray($_aInput) Then Return SetError(1, 0, 0) ; if error set @Error and return 0 Local $iGUIwidth = 900 Local $iGUIheight = 600 Local $iTreeWidth = 150 Local $iCombosZone = 60 Local $hGui = GUICreate("Array viewer", $iGUIwidth, $iGUIheight) Local $StatusBar = _GUICtrlStatusBar_Create($hGui), $iStatusBarheight = 23 Local $aSubscripts[64][4] ; It holds IDs of controls ; - creates all ComboBox in an embedded window. All controls are hidden at startup. ; - Only the necessary combo will be shown at run time. One combo for each dimension Local $hSubscriptSelectors = GUICreate('', $iGUIwidth - $iTreeWidth - 6, $iCombosZone - 2, $iTreeWidth + 4, 2, BitOR($WS_CHILD, $WS_HSCROLL), -1, $hGui) ; GUISetBkColor(0xEEFFEE) For $i = 0 To 63 ; Create the labels $aSubscripts[$i][0] = GUICtrlCreateLabel('D' & $i + 1, ($i * 60) + 8, 1) GUICtrlSetFont(-1, 10, 0, 0, "Courier new") GUICtrlSetState(-1, $GUI_HIDE) ; Labels will be hidden at startup. $aSubscripts[$i][1] = GUICtrlCreateLabel('[', ($i * 60), 18) GUICtrlSetFont(-1, 13, 800) GUICtrlSetState(-1, $GUI_HIDE) $aSubscripts[$i][3] = GUICtrlCreateLabel(']', ($i * 60) + 50, 18) GUICtrlSetFont(-1, 13, 800) GUICtrlSetState(-1, $GUI_HIDE) Next For $i = 0 To 63 ; Create the ComboBox (creates separatelly from labels so that ControlIDs of ComboBaxes has it's own sequence) GUICtrlSetState(-1, $GUI_HIDE) ; ComboBox will be hidden at startup. If $i < 2 Then ; all the content of the first 2 dimensions is already shown in the listview (no need of ComboBox) $aSubscripts[$i][2] = GUICtrlCreateCombo("---", ($i * 60) + 8, 17, 40, -1, $CBS_DROPDOWNLIST) GUICtrlSetState(-1, $GUI_DISABLE) Else $aSubscripts[$i][2] = GUICtrlCreateCombo("0", ($i * 60) + 8, 17, 40, -1, $CBS_DROPDOWNLIST) EndIf GUICtrlSetFont(-1, 8, 800) GUICtrlSetState(-1, $GUI_HIDE) ; ComboBox hidden at startup. Next GUISwitch($hGui) ; back to main window ; Create the TreeView structure $hTree = GUICtrlCreateTreeView(2, 2, $iTreeWidth - 2, $iGUIheight - 4 - $iStatusBarheight, BitOR($TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT, $TVS_DISABLEDRAGDROP, $TVS_SHOWSELALWAYS), $WS_EX_CLIENTEDGE) Local $hRoot = _GUICtrlTreeView_Add($hTree, 0, "Root") ; first insert the root key in treeview _ArrayTraverse($_aInput, $hTree, $hRoot) ; Search for SubArrays (array in array) ; Create the ListView Local $idListview = GUICtrlCreateListView('', $iTreeWidth + 2, $iCombosZone + 2, $iGUIwidth - $iTreeWidth - 4, $iGUIheight - $iCombosZone - 4 - $iStatusBarheight, Default, BitOR($LVS_EX_DOUBLEBUFFER, $LVS_EX_GRIDLINES)) ; If Array has many dimensions, and so all ComboBoxes doesn't fit in window, this allows to scroll GUIRegisterMsg($WM_HSCROLL, "WM_HSCROLL") _GUIScrollBars_Init($hSubscriptSelectors, 60 * UBound($_aInput, 0), 0) GUISetState(@SW_SHOW, $hGui) GUISetState(@SW_SHOW, $hSubscriptSelectors) ; Main Loop until the user exits. ; ------------------------------- Local $sLastWholeKey, $sWholeKey, $vContent, $bRebuild While 1 $Msg = GUIGetMsg() Switch $Msg Case $GUI_EVENT_CLOSE GUIDelete($hGui) ExitLoop Case $aSubscripts[2][2] To $aSubscripts[63][2] ; some ComboBox has changed _ArrayDisplayByLayer($vContent, $idListview, $aSubscripts, False) EndSwitch ; $sWholeKey = _GUICtrlTreeView_GetTree($hTree, _GUICtrlTreeView_GetSelection($hTree)) If $sLastWholeKey <> $sWholeKey Then ; clicked on a new KeyPath or (again) on the one already selected? GUISetCursor(15, 1) ; set cursor to "wait" ; Adapt the TreePath to the array access syntax $sElement = _TreePathParser($sWholeKey) ; address of main array or subarray to peek _GUICtrlStatusBar_SetText($StatusBar, StringReplace($sWholeKey, '|', '->') & ' --> ' & $sElement) ; show the 'address' of selected element on statusbar $vContent = Execute(_TreePathParser($sWholeKey)) _ArrayDisplayByLayer($vContent, $idListview, $aSubscripts, True) _GUICtrlTreeView_ClickItem($hTree, _GUICtrlTreeView_GetSelection($hTree)) $sLastWholeKey = $sWholeKey ; keep track of already clicked KeyPath so we will not redraw the same Array if clicked again GUISetCursor() ; cursor back to default EndIf ; WEnd Return SetError(0, 0, 1) ; if no errors return 1 EndFunc ;==>_ArrayView Func _ArrayDisplayByLayer(ByRef $_aInput, ByRef $idListview, ByRef $aSubscripts, $bRebuild = False) Opt('GUIOnEventMode', 1) ; Disable GUIGetMsg() so is not fired while redrawing ComboBoxes. Local $sTarghet = '$_aInput[$y]' Local $iDimensions = UBound($_aInput, 0) Local $iRows = UBound($_aInput, 1) Local $iColumnsCount, $iColumns = UBound($_aInput, 2) Local $sSubscripts = '' ; Clear the ListView _GUICtrlListView_DeleteAllItems($idListview) If $bRebuild Then ; (Re)Create the ListView $iColumnsCount = _GUICtrlListView_GetColumnCount($idListview) If $iColumnsCount Then For $i = $iColumnsCount To 1 Step -1 _GUICtrlListView_DeleteColumn($idListview, $i - 1) Next EndIf ; Hide and clear all ComboBox For $i = 0 To 63 GUICtrlSetState($aSubscripts[$i][0], $GUI_HIDE) ; Header GUICtrlSetState($aSubscripts[$i][1], $GUI_HIDE) ; '[' GUICtrlSetState($aSubscripts[$i][2], $GUI_HIDE) ; ComboBox Handle GUICtrlSetData($aSubscripts[$i][2], '') ; clear ComboBox items GUICtrlSetState($aSubscripts[$i][3], $GUI_HIDE) ; ']' Next ; (Re)Build the ListView's frame If $iDimensions = 1 Then $iColumns = 1 Else $iColumns = UBound($_aInput, 2) ; nr. of columns in the ListView (second dimension) $sTarghet &= '[$x]' EndIf _GUICtrlListView_AddColumn($idListview, 'Row') For $i = 1 To $iColumns _GUICtrlListView_AddColumn($idListview, 'Col ' & $i - 1, 100) Next For $i = 0 To $iDimensions - 1 ; Show only necessary ComboBox (one for each dimension) GUICtrlSetState($aSubscripts[$i][0], $GUI_SHOW) ; Header GUICtrlSetState($aSubscripts[$i][1], $GUI_SHOW) ; '[' GUICtrlSetState($aSubscripts[$i][2], $GUI_SHOW) ; ComboBox Handle GUICtrlSetState($aSubscripts[$i][3], $GUI_SHOW) ; ']' If $i > 1 Then $sTarghet &= '[0]' ; dimensions over the second all setting to 0 (begin showing first lyer) $sSubscripts = "" For $iSubscript = 0 To UBound($_aInput, $i + 1) - 1 $sSubscripts &= $iSubscript & '|' Next GUICtrlSetData($aSubscripts[$i][2], StringTrimRight($sSubscripts, 1)) ControlFocus('', '', $aSubscripts[$i][2]) ControlSend('', '', $aSubscripts[$i][2], 0) EndIf Next Else ; Just refill the listview with data from the Array dimension selected by ComboBoxes ; Create the 'dimension' string $sTarghet &= '[$x]' For $i = 2 To $iDimensions - 1 $sTarghet &= '[' & GUICtrlRead($aSubscripts[$i][2]) & ']' Next $iColumns = UBound($_aInput, 2) EndIf For $y = 0 To $iRows - 1 GUICtrlCreateListViewItem('', $idListview) _GUICtrlListView_SetItemText($idListview, $y, '[' & $y & ']', 0) ; row number For $x = 0 To $iColumns - 1 $vCellContent = Execute($sTarghet) If IsArray($vCellContent) Then _GUICtrlListView_SetItemText($idListview, $y, '{array}', $x + 1) Else _GUICtrlListView_SetItemText($idListview, $y, $vCellContent, $x + 1) EndIf Next Next Opt('GUIOnEventMode', 0) ; reenable GUIGetMsg() EndFunc ;==>_ArrayDisplayByLayer Func _ArrayTraverse(ByRef $aMyArray, ByRef $hTree, $hParent) #cs since this is a recursive Function, the same Func runs many times, self called from within itself. The variables declared as Global at the top of the script are able to be accessed from any instance of the function, whereas the variable declared (as Local) within the function may be different for each instance of the function. #ce If Not IsArray($aMyArray) Then Return SetError(1, 0, -1) ; we have to know how many nested for-next loops we need ; that is one loop for each dimension Local $iDimensions = UBound($aMyArray, 0) ; number of nested for-next loops Local $sArrayPointer = "$aMyArray", $sElement For $i = 0 To $iDimensions - 1 $sArrayPointer &= '[$aLoops[' & $i & '][2]]' Next ; ----------------------------------------------------------------------------------- ; This is a nested For-Next loops simulator with variable depth of nested loops ; pass a 2D zero based array[n][3] ; with as many records as nested loops needed ; as following: ; ; Example; For $i = start To end ; ----- --- ; [n][0] = Start value ; [n][1] = End value ; [n][2] = actual loop counter (at startup is = to Start value [n][0]) ; ; --- Initializes custom nested For-Next loops -------------------------------------- Local $aLoops[$iDimensions][3] ; nr of nested loops is $iDimensions For $i = 0 To $iDimensions - 1 $aLoops[$i][0] = 0 ; Start value $aLoops[$i][1] = UBound($aMyArray, $i + 1) - 1 ; End value $aLoops[$i][2] = $aLoops[$i][0] ; actual loop counter Next ; ----------------------------------------------------------------------------------- Local $x, $vContent Do $vContent = Execute($sArrayPointer) If IsArray($vContent) Then ; here there is a Nested array, populate the TreeView with a child element $sElement = "" For $i = 0 To $iDimensions - 1 $sElement &= '[' & $aLoops[$i][2] & ']' Next Local $hNode = _GUICtrlTreeView_AddChild($hTree, $hParent, $sElement) ; recursive call for this nested array to search if there are any further nested arrays _ArrayTraverse($vContent, $hTree, $hNode) ; <-- recursive call EndIf ; ------------------------------------------------------------------------------- $x = UBound($aLoops) - 1 $aLoops[$x][2] += 1 While ($aLoops[$x][2] > $aLoops[$x][1]) ; check if and which nested loops are out of bound $aLoops[$x][2] = $aLoops[$x][0] ; reset the counter of this loop ($x) $x -= 1 ; check next outer nest If $x < 0 Then ExitLoop ; if we have finished all nested loops then Exit $aLoops[$x][2] += 1 ; when a deeper loop complete, increment the outer one WEnd Until $x < 0 ; If no more nested loops then exit EndFunc ;==>_ArrayTraverse ; Tree Path to Subscript Func _TreePathParser($Input) Local $sReturn = '$_aInput' Local $aSubArrays = StringSplit($Input, '|', 3) If UBound($aSubArrays) > 1 Then For $i = 1 To UBound($aSubArrays) - 1 $sReturn &= $aSubArrays[$i] If $i < UBound($aSubArrays) - 1 Then $sReturn = '(' & $sReturn & ')' Next EndIf Return $sReturn EndFunc ;==>_TreePathParser ; this will allow the scrolling of window containing ComboBoxes (if number of Combo doesn't fit in window) ; see _GUIScrollBars_Init() in the Help of AutoIt Func WM_HSCROLL($hWnd, $iMsg, $wParam, $lParam) #forceref $iMsg, $lParam Local $iScrollCode = BitAND($wParam, 0x0000FFFF) Local $iIndex = -1, $iCharX, $iPosX Local $iMin, $iMax, $iPage, $iPos, $iTrackPos For $x = 0 To UBound($__g_aSB_WindowInfo) - 1 If $__g_aSB_WindowInfo[$x][0] = $hWnd Then $iIndex = $x $iCharX = $__g_aSB_WindowInfo[$iIndex][2] ExitLoop EndIf Next If $iIndex = -1 Then Return 0 ; ; Get all the horizontal scroll bar information Local $tSCROLLINFO = _GUIScrollBars_GetScrollInfoEx($hWnd, $SB_HORZ) $iMin = DllStructGetData($tSCROLLINFO, "nMin") $iMax = DllStructGetData($tSCROLLINFO, "nMax") $iPage = DllStructGetData($tSCROLLINFO, "nPage") ; Save the position for comparison later on $iPosX = DllStructGetData($tSCROLLINFO, "nPos") $iPos = $iPosX $iTrackPos = DllStructGetData($tSCROLLINFO, "nTrackPos") #forceref $iMin, $iMax Switch $iScrollCode Case $SB_LINELEFT ; user clicked left arrow DllStructSetData($tSCROLLINFO, "nPos", $iPos - 1) Case $SB_LINERIGHT ; user clicked right arrow DllStructSetData($tSCROLLINFO, "nPos", $iPos + 1) Case $SB_PAGELEFT ; user clicked the scroll bar shaft left of the scroll box DllStructSetData($tSCROLLINFO, "nPos", $iPos - $iPage) Case $SB_PAGERIGHT ; user clicked the scroll bar shaft right of the scroll box DllStructSetData($tSCROLLINFO, "nPos", $iPos + $iPage) Case $SB_THUMBTRACK ; user dragged the scroll box DllStructSetData($tSCROLLINFO, "nPos", $iTrackPos) EndSwitch ; // Set the position and then retrieve it. Due to adjustments ; // by Windows it may not be the same as the value set. DllStructSetData($tSCROLLINFO, "fMask", $SIF_POS) _GUIScrollBars_SetScrollInfo($hWnd, $SB_HORZ, $tSCROLLINFO) _GUIScrollBars_GetScrollInfo($hWnd, $SB_HORZ, $tSCROLLINFO) ;// If the position has changed, scroll the window and update it $iPos = DllStructGetData($tSCROLLINFO, "nPos") If ($iPos <> $iPosX) Then _GUIScrollBars_ScrollWindow($hWnd, $iCharX * ($iPosX - $iPos), 0) Return $GUI_RUNDEFMSG EndFunc ;==>WM_HSCROLL
-
I'm trying to have an auto clicker where I save x,y positions and have potential text (like click counter) as well as time between clicks (4 parameters). I'm saving the clicks in an array but can't get the function to work Local $aClicks[3][4] = [[100, 100, "Test", 1000] _ , [200, 200, " Test2", 1500] _ , [200, 200, " Test3", 2000]] Clicking($aClicks) With Clicking being this function Func Clicking($x, $y, $s = "", $z = 1000) But I'm constantly getting an error pointing to "Clicking($aClicks)" and saying Error: Incorrect number of parameters in function call. If I write this instead it works Local $aClicks[3][2] = [[100, 100] _ , [200, 200] _ , [200, 200]] Clicking($aClicks, "Test", 1000) But then I only get the X and Y pos. I just don't understand how the first case is giving me errors, given the array is given 4 parameters to each element, which the function requires.
-
Hello Everyone I have a strange issue ... The json generated array is not getting sorted properly for some reason #include <json.au3> #include <Array.au3> Dim $Chart[0][2] ; Array size of 2 columns $object = json_decode(FileRead("Test.json")) ;for local testing $Coins = json_get($object, '.data') for $i = 0 to UBound($Coins) -1 $name = json_get($object, '.data[' & $i & '].name' ) $change_1h = json_get($object, '.data[' & $i & '].quote.USD.percent_change_1h') _ArrayAdd($Chart,$name & "|" & number($change_1h,3) ) Next _ArraySort($Chart, 1, Default, Default, 1) _ArrayDisplay($Chart) _ArraySort is sorting the array like this (wrong): However if i click on the "Col 1" header it will be sorted correctly: How can i make _ArraySort sort them like clicking on "Col 1" does ? PS: i tried using the function "Number()" when i add the value to the array , but same result .. Thanks in advance Test.json
-
Hi all, I have an array $htags[13][3] where x,0 is a list of html tags divided by "|" (i.e. tag1|tag2|tag3|...) x,1 is 1 or 0 (1 if tag is available in HTML, otherwise 0) x,2 is a string (H1, H2, H3,H4,H5, H6, Title, Keywords, Description, Paragraphs, Anchors, Div, LI) Then I have a Listview: $iLVStyle = BitOR($LVS_REPORT, $LVS_SHOWSELALWAYS) $iLVExtStyle = BitOR($WS_EX_CLIENTEDGE, $LVS_EX_GRIDLINES, $LVS_EX_FULLROWSELECT) $hListView_Tags = GUICtrlCreateListView("H1|H2|H3|H4|H5|H6|Title|Keywords|Description|Paragraphs|Anchors|DIV|LI", 96, 576, 818, 262, $iLVStyle, $iLVExtStyle) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 2, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 3, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 4, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 5, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 6, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 7, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 8, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 9, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 10, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 11, 65) GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 12, 65) It appears like that. I need to fill every columns of the listview with equivalent Tag as in column 2 of $htags This achieved by splitting $aTags = StringSplit($htags[$i][0], "|", 2) I tried this: Func _fillListview($hTags, $hListView_Tags) For $i = 0 To UBound($htags) - 1 ; Split the tags in $htags[$i][0] Local $aTags = StringSplit($htags[$i][0], "|", 2) ; Add a new item to the ListView GUICtrlCreateListViewItem("", $hListView_Tags) ; Loop through the tags and set the corresponding subitem in the ListView For $j = 1 To UBound($aTags) - 1 _GUICtrlListView_SetItem($hListView_Tags, $aTags[$j], $i, $j - 1) Next ; Set the other columns in the ListView _GUICtrlListView_SetItem($hListView_Tags, $htags[$i][1], $i, UBound($aTags) - 1) Next EndFunc But it doesn't work properly. Can someone help me to sort it out? Thanks in advance, Marco
- 12 replies
-
I'd like to take a string like|this and turn it to a 1 key array such as: Array[1] ( [0] => like|this ) There seem to be 2 functions (one internal and the other is an UDF) that are meant for this, but both of which require to supply a delimiter for this to always work. Now of course I can fake a delimiter that I don't expect to exist (like @CRLF). Alternatively, I can use a middleman variable, but it seems like a waste. Is there a more normal (i.e. delimiter and middleman free) way to do it? $foobar = "like|this", $foobar2 = $foobar, $foobar3 = $foobar $foobar = StringSplit($foobar, @CRLF, 3)) ; the delimiter here is a mandatory field ; or include <Array.a3u> $foobar2 = _ArrayFromString($foobar2, @CRLF)) ; the delimiter here is optional but the default "|" will break my string ; or local $foobar_temp[1] = [$foobar3] ; making up a whole new parameter just for this $foobar3 = $foobar_temp
-
Code is simple/selfexplanatory ... #include "Array.au3" $a = StringSplit('aaa,b,cc', ',', 2) ; no_count _ArraySortLen($a) _ArrayDisplay($a, '$a - without count') $b = StringSplit('aaa,b,cc', ',') _ArraySortLen1($b) _ArrayDisplay($b, '$b - with count') ; zero based array (without count at [0]) Func _ArraySortLen(ByRef $aArr, $iDescending = 0) Local $j = UBound($aArr)-1 Local $aTemp[$j+1][2] For $i = 0 To $j $aTemp[$i][0] = StringLen($aArr[$i]) $aTemp[$i][1] = $aArr[$i] Next _ArraySort($aTemp,$iDescending) For $i = 0 To $j $aArr[$i] = $aTemp[$i][1] Next EndFunc ; one based array (with count at [0]) Func _ArraySortLen1(ByRef $aArr, $iDescending = 0) Local $j = $aArr[0] Local $aTemp[$j+1][2] For $i = 1 To $j $aTemp[$i][0] = StringLen($aArr[$i]) $aTemp[$i][1] = $aArr[$i] Next _ArraySort($aTemp,$iDescending,1) For $i = 1 To $j $aArr[$i] = $aTemp[$i][1] Next EndFunc
-
Hello i need help and explanation with loop through 2 arrays here is my code and it works but without loop it just read only 30 lines from sn.txt and i use it line by line to delete rows that includes that values all i need is find the cell with specific code that will be written in sn.txt and delete the entire row and loop it till the end of file Thanks and appreciate the earlier help of yesterday Local $oExcel =_Excel_Open() $datawb = _Excel_BookOpen($oExcel,@ScriptDir & "\agouzaold.xls") $datawb.worksheets("agouzaold").select $LastRow = $datawb.ActiveSheet.UsedRange.Rows.Count $mydata = _Excel_RangeRead($datawb, Default, Default ) _ArrayColDelete($mydata, 0) _ArrayColDelete($mydata, 0) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 2) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 4) _ArrayColDelete($mydata, 4) _ArraySwap($mydata, 0, 2, True) _ArraySwap($mydata, 0, 1, True) _ArraySwap($mydata, 0, 3, True) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, UBound($mydata) - 1) _ArrayDelete($mydata, UBound($mydata) - 1) _Excel_BookClose($datawb) ;-------------------------------- For $i = UBound($mydata) - 1 To 1 Step -1 If Number($mydata[$i][3]) = 0 Then _ArrayDelete($mydata, $i) Next ;-------------------------------- $filea = "sn.txt" Global $filesn[30] _FileReadToArray($filea, $filesn) For $i = UBound($mydata) - 1 To 1 Step -1 If Number($mydata[$i][0]) = $filesn[1] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[2] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[3] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[4] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[5] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[6] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[7] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[8] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[9] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[10] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[11] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[12] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[13] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[14] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[15] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[16] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[17] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[18] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[19] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[20] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[21] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[22] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[23] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[24] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[25] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[26] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[27] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[28] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[29] Then _ArrayDelete($mydata, $i) If Number($mydata[$i][0]) = $filesn[30] Then _ArrayDelete($mydata, $i) Next ;-------------------------------- If IsArray($mydata) Then _ArrayDisplay($mydata)
-
Hello i need some help to remove some rows from the array before i insert it to new excel sheet after i did search all i found was deleting entire empty rows but in my case i want to delete rows only if the "QTY" cell is empty Thanks in advance Func _movetosheet() Local $oExcel =_Excel_Open() sleep(1000) $datawb = _Excel_BookOpen($oExcel,@ScriptDir & "\agouzaold.xls") sleep(1000) $datawb.worksheets("agouzaold").select sleep(1000) $LastRow = $datawb.ActiveSheet.UsedRange.Rows.Count sleep(1000) $mydata = _Excel_RangeRead($datawb, Default, Default ) sleep(1000) _ArrayColDelete($mydata, 0) _ArrayColDelete($mydata, 0) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 1) _ArrayColDelete($mydata, 2) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 3) _ArrayColDelete($mydata, 4) _ArrayColDelete($mydata, 4) sleep(1000) _ArraySwap($mydata, 0, 2, True) _ArraySwap($mydata, 0, 1, True) _ArraySwap($mydata, 0, 3, True) sleep(1000) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) _ArrayDelete($mydata, 0) sleep(1000) _ArrayDelete($mydata, UBound($mydata) - 1) _ArrayDelete($mydata, UBound($mydata) - 1) sleep(1000) ;If IsArray($mydata) Then _ArrayDisplay($mydata) _Excel_BookClose($datawb) sleep(1000) ;-------------------------------- Global $pExcel = _Excel_Open() sleep(1000) Global $oWorkbook = _Excel_BookNew($pExcel, 1) sleep(1000) Global $sWorkbook = @ScriptDir & "\agouza.xlsx" sleep(1000) _Excel_BookSaveAs($oWorkbook, $sWorkbook, $xlWorkbookDefault, True) sleep(1000) _Excel_RangeWrite($oWorkbook, $oWorkbook.Activesheet, $mydata, "a1", Default, True) sleep(1000) _Excel_BookSaveAs($oWorkbook, $sWorkbook, $xlWorkbookDefault, True) Sleep(3000) _Excel_BookClose($oWorkbook) Sleep(3000) $oExcel.Quit() sleep(2000) EndFunc
-
Hello everyone in this example I have an array of 10 elements I'm going through it and I'm finding the largest number I have put a counter to calculate the number of times it repeats. Can you guide me to apply this correctly Best regards #include <MsgBoxConstants.au3> Local $array[10] $array[0]=22 $array[1]=13 $array[2]=11 $array[3]=99 $array[4]=2 $array[5]=17 $array[6]=99 $array[7]=23 $array[8]=99 $array[9]=74 $max=$array[0] $counter=0 For $i = 0 To 9 Step 1 MsgBox($MB_SYSTEMMODAL, "", "The number is!" & @CRLF & $array[$i]) If $array[$i] > $max Then $max=$array[$i] $counter+=1 EndIf Next MsgBox($MB_SYSTEMMODAL, "", "The max value is!" & @CRLF & $max) MsgBox($MB_SYSTEMMODAL, "", "And its repited:" & @CRLF & $counter)
-
This is for extraction of data from HTML tables to an array. It uses an raw html source file as input, and does not relies on any browser. You can get the source of the html using commands like InetGet(), InetRead(), _INetGetSource(), _IEDocReadHTML() for example, or load an html file from disc as well. It also takes care of the data position in the table due to rowspan and colspan trying to keep the same layout in the generated array. It has the option to fill the cells in the array corresponding with the "span" zones all with the same value of the first "span" cell of the corresponding area. ; save this as _HtmlTable2Array.au3 #include-once #include <array.au3> ; ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableGetList ; Description ...: Finds and enumerates all the html tables contained in an html listing (even if nested). ; if the optional parameter $i_index is passed, then only that table is returned ; Syntax ........: _HtmlTableGetList($sHtml[, $i_index = -1]) ; Parameters ....: $sHtml - A string value containing an html page listing ; $i_index - [optional] An integer value indicating the number of the table to be returned (1 based) ; with the default value of -1 an array with all found tables is returned ; Return values .: Success; Returns an 1D 1 based array containing all or single html table found in the html. ; element [0] (and @extended as well) contains the number of tables found (or 0 if no tables are returned) ; if an error occurs then an ampty string is returned and the following @error code is setted ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _HtmlTableGetList($sHtml, $i_index = -1) Local $aTables = _ParseTags($sHtml, "<table", "</table>") If @error Then Return SetError(@error, 0, "") ElseIf $i_index = -1 Then Return SetError(0, $aTables[0], $aTables) Else If $i_index > 0 And $i_index <= $aTables[0] Then Local $aTemp[2] = [1, $aTables[$i_index]] Return SetError(0, 1, $aTemp) Else Return SetError(4, 0, "") ; bad index EndIf EndIf EndFunc ;==>_HtmlTableGetList ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableWriteToArray ; Description ...: It writes values from an html table to a 2D array. It tries to take care of the rowspan and colspan formats ; Syntax ........: _HtmlTableWriteToArray($sHtmlTable[, $bFillSpan = False[, $iFilter = 0]]) ; Parameters ....: $sHtmlTable - A string value containing the html code of the table to be parsed ; $bFillSpan - [optional] Default is False. If span areas have to be filled by repeating the data ; contained in the first cell of the span area ; $iFilter - [optional] Default is 0 (no filters) data extracted from cells is returned unchanged. ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return values .: Success: 2D array containing data from the html table ; Faillure: An empty strimg and sets @error as following: ; @error: 1 - no table content is present in the passed HTML ; 2 - error while parsing rows and/or columns, (opening and closing tags are not balanced) ; 3 - error while parsing rows and/or columns, (open/close mismatch error) ; =============================================================================================================================== Func _HtmlTableWriteToArray($sHtmlTable, $bFillSpan = False, $iFilter = 0) $sHtmlTable = StringReplace(StringReplace($sHtmlTable, "<th", "<td"), "</th>", "</td>") ; th becomes td ; rows of the wanted table Local $iError, $aTempEmptyRow[2] = [1, ""] Local $aRows = _ParseTags($sHtmlTable, "<tr", "</tr>") ; $aRows[0] = nr. of rows If @error Then Return SetError(@error, 0, "") Local $aCols[$aRows[0] + 1], $aTemp For $i = 1 To $aRows[0] $aTemp = _ParseTags($aRows[$i], "<td", "</td>") $iError = @error If $iError = 1 Then ; check if it's an empty row $aTemp = $aTempEmptyRow ; Empty Row Else If $iError Then Return SetError($iError, 0, "") EndIf If $aCols[0] < $aTemp[0] Then $aCols[0] = $aTemp[0] ; $aTemp[0] = max nr. of columns in table $aCols[$i] = $aTemp Next Local $aResult[$aRows[0]][$aCols[0]], $iStart, $iEnd, $aRowspan, $aColspan, $iSpanY, $iSpanX, $iSpanRow, $iSpanCol, $iMarkerCode, $sCellContent Local $aMirror = $aResult For $i = 1 To $aRows[0] ; scan all rows in this table $aTemp = $aCols[$i] ; <td ..> xx </td> ..... For $ii = 1 To $aTemp[0] ; scan all cells in this row $iSpanY = 0 $iSpanX = 0 $iY = $i - 1 ; zero base index for vertical ref $iX = $ii - 1 ; zero based indexes for horizontal ref ; following RegExp kindly provided by SadBunny in this post: ; http://www.autoitscript.com/forum/topic/167174-how-to-get-a-number-located-after-a-name-from-within-a-string/?p=1222781 $aRowspan = StringRegExp($aTemp[$ii], "(?i)rowspan\s*=\s*[""']?\s*(\d+)", 1) ; check presence of rowspan If IsArray($aRowspan) Then $iSpanY = $aRowspan[0] - 1 If $iSpanY + $iY > $aRows[0] Then $iSpanY -= $iSpanY + $iY - $aRows[0] + 1 EndIf EndIf ; $aColspan = StringRegExp($aTemp[$ii], "(?i)colspan\s*=\s*[""']?\s*(\d+)", 1) ; check presence of colspan If IsArray($aColspan) Then $iSpanX = $aColspan[0] - 1 ; $iMarkerCode += 1 ; code to mark this span area or single cell If $iSpanY Or $iSpanX Then $iX1 = $iX For $iSpY = 0 To $iSpanY For $iSpX = 0 To $iSpanX $iSpanRow = $iY + $iSpY If $iSpanRow > UBound($aMirror, 1) - 1 Then $iSpanRow = UBound($aMirror, 1) - 1 EndIf $iSpanCol = $iX1 + $iSpX If $iSpanCol > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][UBound($aResult, 2) + 1] ReDim $aMirror[$aRows[0]][UBound($aMirror, 2) + 1] EndIf ; While $aMirror[$iSpanRow][$iX1 + $iSpX] ; search first free column $iX1 += 1 ; $iSpanCol += 1 If $iX1 + $iSpX > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][UBound($aResult, 2) + 1] ReDim $aMirror[$aRows[0]][UBound($aMirror, 2) + 1] EndIf WEnd Next Next EndIf ; $iX1 = $iX ; following RegExp kindly provided by mikell in this post: ; http://www.autoitscript.com/forum/topic/167309-how-to-remove-from-a-string-all-between-and-pairs/?p=1224207 $sCellContent = StringRegExpReplace($aTemp[$ii], '<[^>]+>', "") If $iFilter Then $sCellContent = _HTML_Filter($sCellContent, $iFilter) For $iSpX = 0 To $iSpanX For $iSpY = 0 To $iSpanY $iSpanRow = $iY + $iSpY If $iSpanRow > UBound($aMirror, 1) - 1 Then $iSpanRow = UBound($aMirror, 1) - 1 EndIf While $aMirror[$iSpanRow][$iX1 + $iSpX] $iX1 += 1 If $iX1 + $iSpX > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][$iX1 + $iSpX + 1] ReDim $aMirror[$aRows[0]][$iX1 + $iSpX + 1] EndIf WEnd $aMirror[$iSpanRow][$iX1 + $iSpX] = $iMarkerCode ; 1 If $bFillSpan Then $aResult[$iSpanRow][$iX1 + $iSpX] = $sCellContent Next $aResult[$iY][$iX1] = $sCellContent Next Next Next ; _ArrayDisplay($aMirror, "Debug") Return SetError(0, $aResult[0][0], $aResult) EndFunc ;==>_HtmlTableWriteToArray ; ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableGetWriteToArray ; Description ...: extract the html code of the required table from the html listing and copy the data of the table to a 2D array ; Syntax ........: _HtmlTableGetWriteToArray($sHtml[, $iWantedTable = 1[, $bFillSpan = False[, $iFilter = 0]]]) ; Parameters ....: $sHtml - A string value containing the html listing ; $iWantedTable - [optional] An integer value. The nr. of the table to be parsed (default is first table) ; $bFillSpan - [optional] Default is False. If all span areas have to be filled by repeating the data ; contained in the first cell of the span area ; $iFilter - [optional] Default is 0 (no filters) data extracted from cells is returned unchanged. ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return values .: success: 2D array containing data from the wanted html table. ; faillure: An empty string and sets @error as following: ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _HtmlTableGetWriteToArray($sHtml, $iWantedTable = 1, $bFillSpan = False, $iFilter = 0) Local $aSingleTable = _HtmlTableGetList($sHtml, $iWantedTable) If @error Then Return SetError(@error, 0, "") Local $aTableData = _HtmlTableWriteToArray($aSingleTable[1], $bFillSpan, $iFilter) If @error Then Return SetError(@error, 0, "") Return SetError(0, $aTableData[0][0], $aTableData) EndFunc ;==>_HtmlTableGetWriteToArray ; #FUNCTION# ==================================================================================================================== ; Name ..........: _ParseTags ; Description ...: searches and extract all portions of html code within opening and closing tags inclusive. ; Returns an array containing a collection of <tag ...... </tag> lines. one in each element (even if are nested) ; Syntax ........: _ParseTags($sHtml, $sOpening, $sClosing) ; Parameters ....: $sHtml - A string value containing the html listing ; $sOpening - A string value indicating the opening tag ; $sClosing - A string value indicating the closing tag ; Return values .: success: an 1D 1 based array containing all the portions of html code representing the element ; element [0] af the array (and @extended as well) contains the counter of found elements ; faillure: An empty string and sets @error as following: ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _ParseTags($sHtml, $sOpening, $sClosing) ; example: $sOpening = '<table', $sClosing = '</table>' ; it finds how many of such tags are on the HTML page StringReplace($sHtml, $sOpening, $sOpening) ; in @xtended nr. of occurences Local $iNrOfThisTag = @extended ; I assume that opening <tag and closing </tag> tags are balanced (as should be) ; (so NO check is made to see if they are actually balanced) If $iNrOfThisTag Then ; if there is at least one of this tag ; $aThisTagsPositions array will contain the positions of the ; starting <tag and ending </tag> tags within the HTML Local $aThisTagsPositions[$iNrOfThisTag * 2 + 1][3] ; 1 based (make room for all open and close tags) ; 2) find in the HTML the positions of the $sOpening <tag and $sClosing </tag> tags For $i = 1 To $iNrOfThisTag $aThisTagsPositions[$i][0] = StringInStr($sHtml, $sOpening, 0, $i) ; start position of $i occurrence of <tag opening tag $aThisTagsPositions[$i][1] = $sOpening ; it marks which kind of tag is this $aThisTagsPositions[$i][2] = $i ; nr of this tag $aThisTagsPositions[$iNrOfThisTag + $i][0] = StringInStr($sHtml, $sClosing, 0, $i) + StringLen($sClosing) - 1 ; end position of $i^ occurrence of </tag> closing tag $aThisTagsPositions[$iNrOfThisTag + $i][1] = $sClosing ; it marks which kind of tag is this Next _ArraySort($aThisTagsPositions, 0, 1) ; now all opening and closing tags are in the same sequence as them appears in the HTML Local $aStack[UBound($aThisTagsPositions)][2] Local $aTags[Ceiling(UBound($aThisTagsPositions) / 2)] ; will contains the collection of <tag ..... </tag> from the html For $i = 1 To UBound($aThisTagsPositions) - 1 If $aThisTagsPositions[$i][1] = $sOpening Then ; opening <tag $aStack[0][0] += 1 ; nr of tags in html $aStack[$aStack[0][0]][0] = $sOpening $aStack[$aStack[0][0]][1] = $i ElseIf $aThisTagsPositions[$i][1] = $sClosing Then ; a closing </tag> was found If Not $aStack[0][0] Or Not ($aStack[$aStack[0][0]][0] = $sOpening And $aThisTagsPositions[$i][1] = $sClosing) Then Return SetError(3, 0, "") ; Open/Close mismatch error Else ; pair detected (the reciprocal tag) ; now get coordinates of the 2 tags ; 1) extract this tag <tag ..... </tag> from the html to the array $aTags[$aThisTagsPositions[$aStack[$aStack[0][0]][1]][2]] = StringMid($sHtml, $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0], 1 + $aThisTagsPositions[$i][0] - $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0]) ; 2) remove that tag <tag ..... </tag> from the html $sHtml = StringLeft($sHtml, $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0] - 1) & StringMid($sHtml, $aThisTagsPositions[$i][0] + 1) ; 3) adjust the references to the new positions of remaining tags For $ii = $i To UBound($aThisTagsPositions) - 1 $aThisTagsPositions[$ii][0] -= StringLen($aTags[$aThisTagsPositions[$aStack[$aStack[0][0]][1]][2]]) Next $aStack[0][0] -= 1 ; nr of tags still in html EndIf EndIf Next If Not $aStack[0][0] Then ; all tags where parsed correctly $aTags[0] = $iNrOfThisTag Return SetError(0, $iNrOfThisTag, $aTags) ; OK Else Return SetError(2, 0, "") ; opening and closing tags are not balanced EndIf Else Return SetError(1, 0, "") ; there are no of such tags on this HTML page EndIf EndFunc ;==>_ParseTags ; #============================================================================= ; Name ..........: _HTML_Filter ; Description ...: Filter for strings ; AutoIt Version : V3.3.0.0 ; Syntax ........: _HTML_Filter(ByRef $sString[, $iMode = 0]) ; Parameter(s): .: $sString - String to filter ; $iMode - Optional: (Default = 0) : removes nothing ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return Value ..: Success - Filterd String ; Failure - Input String ; Author(s) .....: Thorsten Willert, Stephen Podhajecki {gehossafats at netmdc. com} _ConvertEntities ; Date ..........: Wed Jan 27 20:49:59 CET 2010 ; modified ......: by Chimp Removed a double " " entities declaration, ; replace it with char(160) instead of chr(32), ; declaration of the $aEntities array as Static instead of just Local ; ============================================================================== Func _HTML_Filter(ByRef $sString, $iMode = 0) If $iMode = 0 Then Return $sString ;16 simple HTML tag / entities converter If $iMode >= 16 And $iMode < 32 Then Static Local $aEntities[95][2] = [[""", 34],["&", 38],["<", 60],[">", 62],[" ", 160] _ ,["¡", 161],["¢", 162],["£", 163],["¤", 164],["¥", 165],["¦", 166] _ ,["§", 167],["¨", 168],["©", 169],["ª", 170],["¬", 172],["­", 173] _ ,["®", 174],["¯", 175],["°", 176],["±", 177],["²", 178],["³", 179] _ ,["´", 180],["µ", 181],["¶", 182],["·", 183],["¸", 184],["¹", 185] _ ,["º", 186],["»", 187],["¼", 188],["½", 189],["¾", 190],["¿", 191] _ ,["À", 192],["Á", 193],["Ã", 195],["Ä", 196],["Å", 197],["Æ", 198] _ ,["Ç", 199],["È", 200],["É", 201],["Ê", 202],["Ì", 204],["Í", 205] _ ,["Î", 206],["Ï", 207],["Ð", 208],["Ñ", 209],["Ò", 210],["Ó", 211] _ ,["Ô", 212],["Õ", 213],["Ö", 214],["×", 215],["Ø", 216],["Ù", 217] _ ,["Ú", 218],["Û", 219],["Ü", 220],["Ý", 221],["Þ", 222],["ß", 223] _ ,["à", 224],["á", 225],["â", 226],["ã", 227],["ä", 228],["å", 229] _ ,["æ", 230],["ç", 231],["è", 232],["é", 233],["ê", 234],["ë", 235] _ ,["ì", 236],["í", 237],["î", 238],["ï", 239],["ð", 240],["ñ", 241] _ ,["ò", 242],["ó", 243],["ô", 244],["õ", 245],["ö", 246],["÷", 247] _ ,["ø", 248],["ù", 249],["ú", 250],["û", 251],["ü", 252],["þ", 254]] $sString = StringRegExpReplace($sString, '(?i)<p.*?>', @CRLF & @CRLF) $sString = StringRegExpReplace($sString, '(?i)<br>', @CRLF) Local $iE = UBound($aEntities) - 1 For $x = 0 To $iE $sString = StringReplace($sString, $aEntities[$x][0], Chr($aEntities[$x][1]), 0, 2) Next For $x = 32 To 255 $sString = StringReplace($sString, "&#" & $x & ";", Chr($x)) Next $iMode -= 16 EndIf ;8 Tag filter If $iMode >= 8 And $iMode < 16 Then ;$sString = StringRegExpReplace($sString, '<script.*?>.*?</script>', "") $sString = StringRegExpReplace($sString, "<[^>]*>", "") $iMode -= 8 EndIf ; 4 remove all double cr, lf If $iMode >= 4 And $iMode < 8 Then $sString = StringRegExpReplace($sString, "([ \t]*[\n\r]+[ \t]*)", @CRLF) $sString = StringRegExpReplace($sString, "[\n\r]+", @CRLF) $iMode -= 4 EndIf ; 2 remove all double withespaces If $iMode = 2 Or $iMode = 3 Then $sString = StringRegExpReplace($sString, "[[:blank:]]+", " ") $sString = StringRegExpReplace($sString, "\n[[:blank:]]+", @CRLF) $sString = StringRegExpReplace($sString, "[[:blank:]]+\n", "") $iMode -= 2 EndIf ; 1 remove all non ASCII (remove all chars with ascii code > 127) If $iMode = 1 Then $sString = StringRegExpReplace($sString, "[^\x00-\x7F]", " ") EndIf Return $sString EndFunc ;==>_HTML_Filter This simple demo allow to test those functions, showing what it can extract from the html tables in a web page of your choice or loading the html file from the disc. ; #include <_HtmlTable2Array.au3> ; <--- udf already included (hard coded) at bottom of this demo #include <GUIConstantsEx.au3> #include <EditConstants.au3> #include <WindowsConstants.au3> #include <File.au3> ; needed for _FileWriteFromArray() #include <array.au3> #include <IE.au3> Local $oIE1 = _IECreateEmbedded(), $oIE2 = _IECreateEmbedded(), $iFilter = 0 Local $sHtml_File, $iIndex, $aTable, $aMyArray, $sFilePath GUICreate("Html tables to array demo", 1000, 450, (@DesktopWidth - 1000) / 2, (@DesktopHeight - 450) / 2 _ , $WS_OVERLAPPEDWINDOW + $WS_CLIPSIBLINGS + $WS_CLIPCHILDREN) GUICtrlCreateObj($oIE1, 010, 10, 480, 360) ; left browser GUICtrlCreateTab(500, 10, 480, 360) GUICtrlCreateTabItem("view table") GUICtrlCreateObj($oIE2, 502, 33, 474, 335) ; right browser GUICtrlCreateTabItem("view html") Local $idLabel_HtmlTable = GUICtrlCreateInput("", 502, 33, 474, 335, $ES_MULTILINE + $ES_AUTOVSCROLL) GUICtrlSetFont(-1, 10, 0, 0, "Courier new") GUICtrlCreateTabItem("") Local $idInputUrl = GUICtrlCreateInput("", 10, 380, 440, 20) Local $idButton_Go = GUICtrlCreateButton("Go", 455, 380, 25, 20) Local $idButton_Load = GUICtrlCreateButton("Load html from disk", 10, 410, 480, 30) Local $idButton_Prev = GUICtrlCreateButton("Prev <-", 510, 375, 50, 30) Local $idLabel_NunTable = GUICtrlCreateLabel("00 / 00", 570, 375, 40, 30) GUICtrlSetFont(-1, 9, 700) Local $idButton_Next = GUICtrlCreateButton("Next ->", 620, 375, 50, 30) GUICtrlCreateGroup("Fill Span", 680, 370, 80, 40) Local $iFillSpan = GUICtrlCreateCheckbox("", 715, 388, 15, 15) GUICtrlCreateGroup("", -99, -99, 1, 1) ;close group Local $idButton_Array0 = GUICtrlCreateButton("Preview array", 770, 375, 100, 30) Local $idButton_Array1 = GUICtrlCreateButton("Write array to file", 880, 375, 100, 30) ; options for filtering GUICtrlCreateGroup("Filters", 510, 410, 470, 35) Local $iFilter01 = GUICtrlCreateCheckbox("non ascii", 520, 425, 85, 15) Local $iFilter02 = GUICtrlCreateCheckbox("double spaces", 610, 425, 85, 15) Local $iFilter04 = GUICtrlCreateCheckbox("double @LF", 700, 425, 85, 15) Local $iFilter08 = GUICtrlCreateCheckbox("html-tags", 790, 425, 85, 15) Local $iFilter16 = GUICtrlCreateCheckbox("tags to entities", 880, 425, 85, 15) GUICtrlCreateGroup("", -99, -99, 1, 1) ;close group GUISetState(@SW_SHOW) ;Show GUI ; _IEDocWriteHTML($oIE2, "<HTML></HTML>") GUICtrlSetData($idInputUrl, "http://www.danshort.com/HTMLentities/") ; GUICtrlSetData($idInputUrl, "http://www.mojotoad.com/sisk/projects/HTML-TableExtract/tables.html") ; example page ControlClick("", "", $idButton_Go) ; _IEAction($oIE1, "stop") Do; Waiting for user to close the window $iMsg = GUIGetMsg() Select Case $iMsg = $idButton_Go _IENavigate($oIE1, GUICtrlRead($idInputUrl)) ; _IEAction($oIE1, "stop") $aTables = _HtmlTableGetList(_IEBodyReadHTML($oIE1)) If Not @error Then ; _ArrayDisplay($aTables, "Tables contained in this html") $iIndex = 1 _IEBodyWriteHTML($oIE2, "<html>" & $aTables[$iIndex] & "</html>") ControlClick("", "", $idButton_Prev) _IEAction($oIE2, "stop") Else MsgBox(0, 0, "@error " & @error) EndIf Case $iMsg = $idButton_Load ConsoleWrite("$idButton_Load" & @CRLF) $sHtml_File = FileOpenDialog("Choose an html file", @ScriptDir & "\", "html page (*.htm;*.html)") If Not @error Then GUICtrlSetData($idInputUrl, $sHtml_File) ControlClick("", "", $idButton_Go) EndIf Case $iMsg = $idButton_Next If IsArray($aTables) Then $iIndex += $iIndex < $aTables[0] GUICtrlSetData($idLabel_NunTable, "Table" & @CRLF & $iIndex & " / " & $aTables[0]) GUICtrlSetData($idLabel_HtmlTable, $aTables[$iIndex]) _IEBodyWriteHTML($oIE2, "<html>" & $aTables[$iIndex] & "</html>") _IEAction($oIE2, "stop") EndIf Case $iMsg = $idButton_Prev If IsArray($aTables) Then $iIndex -= $iIndex > 1 GUICtrlSetData($idLabel_NunTable, "Table" & @CRLF & $iIndex & " / " & $aTables[0]) GUICtrlSetData($idLabel_HtmlTable, $aTables[$iIndex]) _IEBodyWriteHTML($oIE2, "<html>" & $aTables[$iIndex] & "</html>") _IEAction($oIE2, "stop") EndIf Case $iMsg = $idButton_Array0 ; Preview Array If IsArray($aTables) Then $iFilter = 1 * _IsChecked($iFilter01) + 2 * _IsChecked($iFilter02) + 4 * _IsChecked($iFilter04) + 8 * _IsChecked($iFilter08) + 16 * _IsChecked($iFilter16) $aMyArray = _HtmlTableWriteToArray($aTables[$iIndex], _IsChecked($iFillSpan), $iFilter) If Not @error Then _ArrayDisplay($aMyArray) EndIf Case $iMsg = $idButton_Array1 ; Saves the array in a csv file of your choice If IsArray($aTables) Then $iFilter = 1 * _IsChecked($iFilter01) + 2 * _IsChecked($iFilter02) + 4 * _IsChecked($iFilter04) + 8 * _IsChecked($iFilter08) + 16 * _IsChecked($iFilter16) $aMyArray = _HtmlTableWriteToArray($aTables[$iIndex], _IsChecked($iFillSpan), $iFilter) If Not @error Then $sFilePath = FileSaveDialog("Choose a file to save to", @ScriptDir, "(*.csv)") If $sFilePath <> "" Then If Not _FileWriteFromArray($sFilePath, $aMyArray, 0, Default, ",") Then MsgBox(0, "Error on file write", "Error code is " & @error & @CRLF & @CRLF & "@error meaning:" & @CRLF & _ "1 - Error opening specified file" & @CRLF & _ "2 - $aArray is not an array" & @CRLF & _ "3 - Error writing to file" & @CRLF & _ "4 - $aArray is not a 1D or 2D array" & @CRLF & _ "5 - Start index is greater than the $iUbound parameter") EndIf EndIf EndIf EndIf EndSelect Until $iMsg = $GUI_EVENT_CLOSE GUIDelete() ; returns 1 if CheckBox is checked Func _IsChecked($idControlID) ; $GUI_CHECKED = 1 Return GUICtrlRead($idControlID) = $GUI_CHECKED EndFunc ;==>_IsChecked ; ------------------------------------------------------------------------ ; Following code should be included by the #include <_HtmlTable2Array.au3> ; hard coded here for easy load an run to try the example ; ------------------------------------------------------------------------ #include-once #include <array.au3> ; ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableGetList ; Description ...: Finds and enumerates all the html tables contained in an html listing (even if nested). ; if the optional parameter $i_index is passed, then only that table is returned ; Syntax ........: _HtmlTableGetList($sHtml[, $i_index = -1]) ; Parameters ....: $sHtml - A string value containing an html page listing ; $i_index - [optional] An integer value indicating the number of the table to be returned (1 based) ; with the default value of -1 an array with all found tables is returned ; Return values .: Success; Returns an 1D 1 based array containing all or single html table found in the html. ; element [0] (and @extended as well) contains the number of tables found (or 0 if no tables are returned) ; if an error occurs then an ampty string is returned and the following @error code is setted ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _HtmlTableGetList($sHtml, $i_index = -1) Local $aTables = _ParseTags($sHtml, "<table", "</table>") If @error Then Return SetError(@error, 0, "") ElseIf $i_index = -1 Then Return SetError(0, $aTables[0], $aTables) Else If $i_index > 0 And $i_index <= $aTables[0] Then Local $aTemp[2] = [1, $aTables[$i_index]] Return SetError(0, 1, $aTemp) Else Return SetError(4, 0, "") ; bad index EndIf EndIf EndFunc ;==>_HtmlTableGetList ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableWriteToArray ; Description ...: It writes values from an html table to a 2D array. It tries to take care of the rowspan and colspan formats ; Syntax ........: _HtmlTableWriteToArray($sHtmlTable[, $bFillSpan = False[, $iFilter = 0]]) ; Parameters ....: $sHtmlTable - A string value containing the html code of the table to be parsed ; $bFillSpan - [optional] Default is False. If span areas have to be filled by repeating the data ; contained in the first cell of the span area ; $iFilter - [optional] Default is 0 (no filters) data extracted from cells is returned unchanged. ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return values .: Success: 2D array containing data from the html table ; Faillure: An empty strimg and sets @error as following: ; @error: 1 - no table content is present in the passed HTML ; 2 - error while parsing rows and/or columns, (opening and closing tags are not balanced) ; 3 - error while parsing rows and/or columns, (open/close mismatch error) ; =============================================================================================================================== Func _HtmlTableWriteToArray($sHtmlTable, $bFillSpan = False, $iFilter = 0) $sHtmlTable = StringReplace(StringReplace($sHtmlTable, "<th", "<td"), "</th>", "</td>") ; th becomes td ; rows of the wanted table Local $iError, $aTempEmptyRow[2] = [1, ""] Local $aRows = _ParseTags($sHtmlTable, "<tr", "</tr>") ; $aRows[0] = nr. of rows If @error Then Return SetError(@error, 0, "") Local $aCols[$aRows[0] + 1], $aTemp For $i = 1 To $aRows[0] $aTemp = _ParseTags($aRows[$i], "<td", "</td>") $iError = @error If $iError = 1 Then ; check if it's an empty row $aTemp = $aTempEmptyRow ; Empty Row Else If $iError Then Return SetError($iError, 0, "") EndIf If $aCols[0] < $aTemp[0] Then $aCols[0] = $aTemp[0] ; $aTemp[0] = max nr. of columns in table $aCols[$i] = $aTemp Next Local $aResult[$aRows[0]][$aCols[0]], $iStart, $iEnd, $aRowspan, $aColspan, $iSpanY, $iSpanX, $iSpanRow, $iSpanCol, $iMarkerCode, $sCellContent Local $aMirror = $aResult For $i = 1 To $aRows[0] ; scan all rows in this table $aTemp = $aCols[$i] ; <td ..> xx </td> ..... For $ii = 1 To $aTemp[0] ; scan all cells in this row $iSpanY = 0 $iSpanX = 0 $iY = $i - 1 ; zero base index for vertical ref $iX = $ii - 1 ; zero based indexes for horizontal ref ; following RegExp kindly provided by SadBunny in this post: ; http://www.autoitscript.com/forum/topic/167174-how-to-get-a-number-located-after-a-name-from-within-a-string/?p=1222781 $aRowspan = StringRegExp($aTemp[$ii], "(?i)rowspan\s*=\s*[""']?\s*(\d+)", 1) ; check presence of rowspan If IsArray($aRowspan) Then $iSpanY = $aRowspan[0] - 1 If $iSpanY + $iY > $aRows[0] Then $iSpanY -= $iSpanY + $iY - $aRows[0] + 1 EndIf EndIf ; $aColspan = StringRegExp($aTemp[$ii], "(?i)colspan\s*=\s*[""']?\s*(\d+)", 1) ; check presence of colspan If IsArray($aColspan) Then $iSpanX = $aColspan[0] - 1 ; $iMarkerCode += 1 ; code to mark this span area or single cell If $iSpanY Or $iSpanX Then $iX1 = $iX For $iSpY = 0 To $iSpanY For $iSpX = 0 To $iSpanX $iSpanRow = $iY + $iSpY If $iSpanRow > UBound($aMirror, 1) - 1 Then $iSpanRow = UBound($aMirror, 1) - 1 EndIf $iSpanCol = $iX1 + $iSpX If $iSpanCol > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][UBound($aResult, 2) + 1] ReDim $aMirror[$aRows[0]][UBound($aMirror, 2) + 1] EndIf ; While $aMirror[$iSpanRow][$iX1 + $iSpX] ; search first free column $iX1 += 1 ; $iSpanCol += 1 If $iX1 + $iSpX > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][UBound($aResult, 2) + 1] ReDim $aMirror[$aRows[0]][UBound($aMirror, 2) + 1] EndIf WEnd Next Next EndIf ; $iX1 = $iX ; following RegExp kindly provided by mikell in this post: ; http://www.autoitscript.com/forum/topic/167309-how-to-remove-from-a-string-all-between-and-pairs/?p=1224207 $sCellContent = StringRegExpReplace($aTemp[$ii], '<[^>]+>', "") If $iFilter Then $sCellContent = _HTML_Filter($sCellContent, $iFilter) For $iSpX = 0 To $iSpanX For $iSpY = 0 To $iSpanY $iSpanRow = $iY + $iSpY If $iSpanRow > UBound($aMirror, 1) - 1 Then $iSpanRow = UBound($aMirror, 1) - 1 EndIf While $aMirror[$iSpanRow][$iX1 + $iSpX] $iX1 += 1 If $iX1 + $iSpX > UBound($aMirror, 2) - 1 Then ReDim $aResult[$aRows[0]][$iX1 + $iSpX + 1] ReDim $aMirror[$aRows[0]][$iX1 + $iSpX + 1] EndIf WEnd $aMirror[$iSpanRow][$iX1 + $iSpX] = $iMarkerCode ; 1 If $bFillSpan Then $aResult[$iSpanRow][$iX1 + $iSpX] = $sCellContent Next $aResult[$iY][$iX1] = $sCellContent Next Next Next ; _ArrayDisplay($aMirror, "Debug") Return SetError(0, $aResult[0][0], $aResult) EndFunc ;==>_HtmlTableWriteToArray ; ; #FUNCTION# ==================================================================================================================== ; Name ..........: _HtmlTableGetWriteToArray ; Description ...: extract the html code of the required table from the html listing and copy the data of the table to a 2D array ; Syntax ........: _HtmlTableGetWriteToArray($sHtml[, $iWantedTable = 1[, $bFillSpan = False[, $iFilter = 0]]]) ; Parameters ....: $sHtml - A string value containing the html listing ; $iWantedTable - [optional] An integer value. The nr. of the table to be parsed (default is first table) ; $bFillSpan - [optional] Default is False. If all span areas have to be filled by repeating the data ; contained in the first cell of the span area ; $iFilter - [optional] Default is 0 (no filters) data extracted from cells is returned unchanged. ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return values .: success: 2D array containing data from the wanted html table. ; faillure: An empty string and sets @error as following: ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _HtmlTableGetWriteToArray($sHtml, $iWantedTable = 1, $bFillSpan = False, $iFilter = 0) Local $aSingleTable = _HtmlTableGetList($sHtml, $iWantedTable) If @error Then Return SetError(@error, 0, "") Local $aTableData = _HtmlTableWriteToArray($aSingleTable[1], $bFillSpan, $iFilter) If @error Then Return SetError(@error, 0, "") Return SetError(0, $aTableData[0][0], $aTableData) EndFunc ;==>_HtmlTableGetWriteToArray ; #FUNCTION# ==================================================================================================================== ; Name ..........: _ParseTags ; Description ...: searches and extract all portions of html code within opening and closing tags inclusive. ; Returns an array containing a collection of <tag ...... </tag> lines. one in each element (even if are nested) ; Syntax ........: _ParseTags($sHtml, $sOpening, $sClosing) ; Parameters ....: $sHtml - A string value containing the html listing ; $sOpening - A string value indicating the opening tag ; $sClosing - A string value indicating the closing tag ; Return values .: success: an 1D 1 based array containing all the portions of html code representing the element ; element [0] af the array (and @extended as well) contains the counter of found elements ; faillure: An empty string and sets @error as following: ; @error: 1 - no tables are present in the passed HTML ; 2 - error while parsing tables, (opening and closing tags are not balanced) ; 3 - error while parsing tables, (open/close mismatch error) ; 4 - invalid table index request (requested table nr. is out of boundaries) ; =============================================================================================================================== Func _ParseTags($sHtml, $sOpening, $sClosing) ; example: $sOpening = '<table', $sClosing = '</table>' ; it finds how many of such tags are on the HTML page StringReplace($sHtml, $sOpening, $sOpening) ; in @xtended nr. of occurences Local $iNrOfThisTag = @extended ; I assume that opening <tag and closing </tag> tags are balanced (as should be) ; (so NO check is made to see if they are actually balanced) If $iNrOfThisTag Then ; if there is at least one of this tag ; $aThisTagsPositions array will contain the positions of the ; starting <tag and ending </tag> tags within the HTML Local $aThisTagsPositions[$iNrOfThisTag * 2 + 1][3] ; 1 based (make room for all open and close tags) ; 2) find in the HTML the positions of the $sOpening <tag and $sClosing </tag> tags For $i = 1 To $iNrOfThisTag $aThisTagsPositions[$i][0] = StringInStr($sHtml, $sOpening, 0, $i) ; start position of $i occurrence of <tag opening tag $aThisTagsPositions[$i][1] = $sOpening ; it marks which kind of tag is this $aThisTagsPositions[$i][2] = $i ; nr of this tag $aThisTagsPositions[$iNrOfThisTag + $i][0] = StringInStr($sHtml, $sClosing, 0, $i) + StringLen($sClosing) - 1 ; end position of $i^ occurrence of </tag> closing tag $aThisTagsPositions[$iNrOfThisTag + $i][1] = $sClosing ; it marks which kind of tag is this Next _ArraySort($aThisTagsPositions, 0, 1) ; now all opening and closing tags are in the same sequence as them appears in the HTML Local $aStack[UBound($aThisTagsPositions)][2] Local $aTags[Ceiling(UBound($aThisTagsPositions) / 2)] ; will contains the collection of <tag ..... </tag> from the html For $i = 1 To UBound($aThisTagsPositions) - 1 If $aThisTagsPositions[$i][1] = $sOpening Then ; opening <tag $aStack[0][0] += 1 ; nr of tags in html $aStack[$aStack[0][0]][0] = $sOpening $aStack[$aStack[0][0]][1] = $i ElseIf $aThisTagsPositions[$i][1] = $sClosing Then ; a closing </tag> was found If Not $aStack[0][0] Or Not ($aStack[$aStack[0][0]][0] = $sOpening And $aThisTagsPositions[$i][1] = $sClosing) Then Return SetError(3, 0, "") ; Open/Close mismatch error Else ; pair detected (the reciprocal tag) ; now get coordinates of the 2 tags ; 1) extract this tag <tag ..... </tag> from the html to the array $aTags[$aThisTagsPositions[$aStack[$aStack[0][0]][1]][2]] = StringMid($sHtml, $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0], 1 + $aThisTagsPositions[$i][0] - $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0]) ; 2) remove that tag <tag ..... </tag> from the html $sHtml = StringLeft($sHtml, $aThisTagsPositions[$aStack[$aStack[0][0]][1]][0] - 1) & StringMid($sHtml, $aThisTagsPositions[$i][0] + 1) ; 3) adjust the references to the new positions of remaining tags For $ii = $i To UBound($aThisTagsPositions) - 1 $aThisTagsPositions[$ii][0] -= StringLen($aTags[$aThisTagsPositions[$aStack[$aStack[0][0]][1]][2]]) Next $aStack[0][0] -= 1 ; nr of tags still in html EndIf EndIf Next If Not $aStack[0][0] Then ; all tags where parsed correctly $aTags[0] = $iNrOfThisTag Return SetError(0, $iNrOfThisTag, $aTags) ; OK Else Return SetError(2, 0, "") ; opening and closing tags are not balanced EndIf Else Return SetError(1, 0, "") ; there are no of such tags on this HTML page EndIf EndFunc ;==>_ParseTags ; #============================================================================= ; Name ..........: _HTML_Filter ; Description ...: Filter for strings ; AutoIt Version : V3.3.0.0 ; Syntax ........: _HTML_Filter(ByRef $sString[, $iMode = 0]) ; Parameter(s): .: $sString - String to filter ; $iMode - Optional: (Default = 0) : removes nothing ; - 0 = no filter ; - 1 = removes non ascii characters ; - 2 = removes all double whitespaces ; - 4 = removes all double linefeeds ; - 8 = removes all html-tags ; - 16 = simple html-tag / entities convertor ; Return Value ..: Success - Filterd String ; Failure - Input String ; Author(s) .....: Thorsten Willert, Stephen Podhajecki {gehossafats at netmdc. com} _ConvertEntities ; Date ..........: Wed Jan 27 20:49:59 CET 2010 ; modified ......: by Chimp Removed a double " " entities declaration, ; replace it with char(160) instead of chr(32), ; declaration of the $aEntities array as Static instead of just Local ; ============================================================================== Func _HTML_Filter(ByRef $sString, $iMode = 0) If $iMode = 0 Then Return $sString ;16 simple HTML tag / entities converter If $iMode >= 16 And $iMode < 32 Then Static Local $aEntities[95][2] = [[""", 34],["&", 38],["<", 60],[">", 62],[" ", 160] _ ,["¡", 161],["¢", 162],["£", 163],["¤", 164],["¥", 165],["¦", 166] _ ,["§", 167],["¨", 168],["©", 169],["ª", 170],["¬", 172],["­", 173] _ ,["®", 174],["¯", 175],["°", 176],["±", 177],["²", 178],["³", 179] _ ,["´", 180],["µ", 181],["¶", 182],["·", 183],["¸", 184],["¹", 185] _ ,["º", 186],["»", 187],["¼", 188],["½", 189],["¾", 190],["¿", 191] _ ,["À", 192],["Á", 193],["Ã", 195],["Ä", 196],["Å", 197],["Æ", 198] _ ,["Ç", 199],["È", 200],["É", 201],["Ê", 202],["Ì", 204],["Í", 205] _ ,["Î", 206],["Ï", 207],["Ð", 208],["Ñ", 209],["Ò", 210],["Ó", 211] _ ,["Ô", 212],["Õ", 213],["Ö", 214],["×", 215],["Ø", 216],["Ù", 217] _ ,["Ú", 218],["Û", 219],["Ü", 220],["Ý", 221],["Þ", 222],["ß", 223] _ ,["à", 224],["á", 225],["â", 226],["ã", 227],["ä", 228],["å", 229] _ ,["æ", 230],["ç", 231],["è", 232],["é", 233],["ê", 234],["ë", 235] _ ,["ì", 236],["í", 237],["î", 238],["ï", 239],["ð", 240],["ñ", 241] _ ,["ò", 242],["ó", 243],["ô", 244],["õ", 245],["ö", 246],["÷", 247] _ ,["ø", 248],["ù", 249],["ú", 250],["û", 251],["ü", 252],["þ", 254]] $sString = StringRegExpReplace($sString, '(?i)<p.*?>', @CRLF & @CRLF) $sString = StringRegExpReplace($sString, '(?i)<br>', @CRLF) Local $iE = UBound($aEntities) - 1 For $x = 0 To $iE $sString = StringReplace($sString, $aEntities[$x][0], Chr($aEntities[$x][1]), 0, 2) Next For $x = 32 To 255 $sString = StringReplace($sString, "&#" & $x & ";", Chr($x)) Next $iMode -= 16 EndIf ;8 Tag filter If $iMode >= 8 And $iMode < 16 Then ;$sString = StringRegExpReplace($sString, '<script.*?>.*?</script>', "") $sString = StringRegExpReplace($sString, "<[^>]*>", "") $iMode -= 8 EndIf ; 4 remove all double cr, lf If $iMode >= 4 And $iMode < 8 Then $sString = StringRegExpReplace($sString, "([ \t]*[\n\r]+[ \t]*)", @CRLF) $sString = StringRegExpReplace($sString, "[\n\r]+", @CRLF) $iMode -= 4 EndIf ; 2 remove all double withespaces If $iMode = 2 Or $iMode = 3 Then $sString = StringRegExpReplace($sString, "[[:blank:]]+", " ") $sString = StringRegExpReplace($sString, "\n[[:blank:]]+", @CRLF) $sString = StringRegExpReplace($sString, "[[:blank:]]+\n", "") $iMode -= 2 EndIf ; 1 remove all non ASCII (remove all chars with ascii code > 127) If $iMode = 1 Then $sString = StringRegExpReplace($sString, "[^\x00-\x7F]", " ") EndIf Return $sString EndFunc ;==>_HTML_Filter Any error reports or suggestions for enhancements are welcome
-
Hi, I was looking into creating a script that would detect if a file exists, then move it (and in some cases rename it, depending on the file) as well as write to a log file. The issue is, there is a lot of files that need to be moved, sometimes some files will exist and others won't depending on the use-case. However if a file does exist, it will always be going into the same directory with the same name. Currently I have an array nested inside of the array, with each array inside that array having both the old and new directory, and then a For loop to actually run through and do the file transferring. The issue I am having is how to call the Array inside of the array, because how do I specify which the old directory is and which the new is? Global $FileTransfer[2000] = [Global $Dir1[2] = ["original dir 1", "new dir 1"], Global $Dir2[2] = ["original dir 2", "new dir 2"]] For $FileTransfer = [0] To [1] Step +1 If FileExists({original dir}) Then FileMove({original dir}, new dir, 1) FileOpen("log.latest.txt", 1) FileWrite("log.latest.txt", "{original dir} found, moved it to new dir." & @CRLF) FileClose("log.latest.txt") Else FileOpen("log_latest.txt", 1) FileWrite("log_latest.txt", "{original dir} not found, ignoreing it." & @CRLF) FileClose("log_latest.txt") EndIf Next I have put what I want the old and new directory to be for each array in {}, so hopefully its easier to tell which part is working and whats not. I am still reasonably new to AutoIT, any help is appreciated. Thankyou
-
The _XLSXReadToArray Fuction Reads the EXCEL XLSX Sheet into an Array, not needed that Office is installed and do not use Object just use the REGEXP so_XLSXReadToArray works very fast, in a test done by me here with BulletinSearch_20121008_170143.xlsx (1,5 Mb, Rows = 12148 & Column = 15), the _XLSXReadToArray Return Array in 10 seconds, instead to Excel 2013 them have served more than 20 seconds to open the file ect ect, Normally should not happen ever of not finding the "[Content_Types].xml" or other files mentioned in "[Content_Types].xml", but if anything happens already Added the >_FileListToArrayEx to try to search the *.xml files in "Temp Extract Diretory" #include-once ; #UDF# ======================================================================================================================= ; Title .........: XLSX Read To Array ; AutoIt Version : 3.3.8.1 ; Language ......: English ; Description ...: Fuction Reads the EXCEL XLSX Sheet into an Array ; Author(s) .....: DXRW4E ; Notes .........: ; =============================================================================================================================== ; #CURRENT# ===================================================================================================================== ;~ _XLSXReadToArray ;~ _XLSXSheetGetColumnNumber ;~ _SSNToDate ;~ _DateToSSN ;~ _FileListToArrayEx ; =============================================================================================================================== If Not ObjEvent("AutoIt.Error") Then Global Const $_XLSXZip_COMErrorFunc = ObjEvent("AutoIt.Error", "_XLSXZip_COMErrorFunc") Global $DateSSN[27] = [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] ; #FUNCTION# ================================================================================================================================ ; Name...........: _XLSXReadToArray ; Description ...: The _XLSXReadToArray Fuction Reads the EXCEL XLSX Sheet into an Array ; Syntax.........: _XLSXReadToArray($XLSXFilePath, $iFlag) ; Parameters ....: $XLSXFilePath - Path and filename of the XLSX file to be read. ; $iFlag - Optional ; |$iFlag = 0 (Default) None ; |$iFlag = 1 if there are also add HyperLinks in the Array ; Strings\Test in Column\Rows will separate from HyperLink by @LF, example "Value" & @LF & http://www.autoitscript.com/forum/ ; |$Cols - Optional, Columns Number to Read (read only X column) ; |$Rows - Optional, Rows Number to Read (read only X Row) ; |$iSheet - Optional, Number of Sheet*.xml to Read, Default is 1 ; Return values .: Success - Return ; Array ($Array[0][0] = Rows Number & @Extended = Column Nmmber) ; If Set $Cols and $Rows Return is String Data, if Return Strigs = "" @Extended is Set to 1 ; @Error - Set Error ; |1 = XLSX file not found or invalid (Can not Read\Extract XLSX file) ; |2 = [Content_Types].xml not found or invalid ; |3 = sheet1.xml file not found or invalid ; |4 = Sheet Dimension Not found Or is Greater than 15999999 (Array Size Limit) ; |5 = No SheetDate (Columns & Rows) Found ; Author ........: DXRW4E ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: __XLSXReadToArray("C:\file.xlsx") ; Note ..........: ; =========================================================================================================================================== Func _XLSXReadToArray($XLSXFilePath, $iFlag = 0, $Cols = 0, $Rows = 0, $iSheet = 1) If ($Cols * ($Rows + 1)) > 15999999 Then Return SetError(4, 0, "") Local $XLSXExtractDir = @WindowsDir & "\Temp\XLSX_" & @YEAR & @MON & @MDAY & @HOUR & @MIN & @SEC & @MSEC, $XLSXZip, $oShell, $X $XLSXZip = FileCopy($XLSXFilePath, $XLSXExtractDir & "\__xlsx.zip", 9) If Not $XLSXZip Then Return SetError(1, DirRemove($XLSXExtractDir, 1), "") $oShell = ObjCreate("shell.application") $oShell.Namespace($XLSXExtractDir).CopyHere($oShell.Namespace($XLSXExtractDir & "\__xlsx.zip").items, 20) Local $ContentTypesXML = StringReplace(FileRead($XLSXExtractDir & "\[Content_Types].xml"), "/", "\", 0, 1) If Not $ContentTypesXML Then $ContentTypesXML = _FileListToArrayEx($XLSXExtractDir, "*Content*Types*.xml", 37) If Not @Error Then $ContentTypesXML = StringReplace(FileRead($XLSXExtractDir & "\" & $ContentTypesXML[0]), "/", "\", 0, 1) If Not $ContentTypesXML Then Return SetError(2, DirRemove($XLSXExtractDir, 1), "") EndIf Local $SharedStringsXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\sharedStrings\.xml)"', 1) If @Error Then $SharedStringsXMLPath = _FileListToArrayEx($XLSXExtractDir, "sharedStrings.xml", 165) If Not @Error Then $SharedStringsXMLPath = $XLSXExtractDir & $SharedStringsXMLPath[0] Local $SheetXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\sheet' & $iSheet & '\.xml)"', 1) If @Error Then $SheetXMLPath = _FileListToArrayEx($XLSXExtractDir, "sheet" & $iSheet & ".xml", 165) If @Error Then $SheetXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\sheet[^"]*\.xml)"', 1) If @Error Then $SheetXMLPath = _FileListToArrayEx($XLSXExtractDir, "sheet*.xml", 165) If Not @Error Then $SheetXMLPath = $XLSXExtractDir & $SheetXMLPath[0] Local $WorkSheet = FileRead($SheetXMLPath) If Not $WorkSheet Then Return SetError(3, DirRemove($XLSXExtractDir, 1), "") Local $SharedStringsXML = FileRead($SharedStringsXMLPath) ;; Example Get File Path using the StringRegExpReplace(), but more slowly than StringRegExp Mod. ;; Local $WorkBookXMLPath = $XLSXExtractDir & StringRegExpReplace($ContentTypesXML, '(?si).*<Override\s+PartName="([^"]*\\workbook\.xml)".*', "$1") ;; Local $StylesXMLPath = $XLSXExtractDir & StringRegExpReplace($ContentTypesXML, '(?si).*<Override\s+PartName="([^"]*\\styles\.xml)".*', "$1") ;; Local $SharedStringsXMLPath = $XLSXExtractDir & StringRegExpReplace($ContentTypesXML, '(?si).*<Override\s+PartName="([^"]*\\sharedStrings\.xml)".*', "$1") ;; Local $SheetXMLPath = $XLSXExtractDir & StringRegExpReplace($ContentTypesXML, '(?si).*<Override\s+PartName="([^"]*\\sheet1\.xml)".*', "$1") ;; ;; ;; read other ect ect ect ;; Local $WorkBookXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\workbook\.xml)"', 1) ;; If @Error Then $WorkBookXMLPath = _FileListToArrayEx($XLSXExtractDir, "workbook.xml", 165) ;; If Not @Error Then $WorkBookXMLPath = $XLSXExtractDir & $WorkBookXMLPath[0] ;; $WorkBookXML = FileRead($WorkBookXMLPath) ;; ;Example using the StringRegExpReplace() ;; Local $SheetName = $XLSXExtractDir & StringRegExpReplace($WorkBookXML, '(?si).*<sheet\s+name="([^"]*)".*', "$1") ;; ;; Local $AppXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\app\.xml)"', 1) ;; If @Error Then $AppXMLPath = _FileListToArrayEx($XLSXExtractDir, "app.xml", 165) ;; If Not @Error Then $AppXMLPath = $XLSXExtractDir & $AppXMLPath[0] ;; $AppXML = FileRead($AppXMLPath) ;; ;Example using the StringRegExpReplace() ;; Local $AppVersion = $XLSXExtractDir & StringRegExpReplace($AppXML, '(?si).*<AppVersion>([^<]*)</AppVersion>.*', "$1") ;; ;; Local $CoreXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\core\.xml)"', 1) ;; If @Error Then $CoreXMLPath = _FileListToArrayEx($XLSXExtractDir, "core.xml", 165) ;; If Not @Error Then $CoreXMLPath = $XLSXExtractDir & $CoreXMLPath[0] ;; $CoreXML = FileRead($CoreXMLPath) ;; ;Example using the StringRegExpReplace() ;; Local $Modified = $XLSXExtractDir & StringRegExpReplace($CoreXML, '(?si).*<dcterms\:modified[^>]([^<]*)</dcterms:modified>.*', "$1") ;; ;; Local $StylesXMLPath = StringRegExp($ContentTypesXML, '(?si)<Override\s*PartName="([^"]*\\styles\.xml)"', 1) ;; If @Error Then $StylesXMLPath = _FileListToArrayEx($XLSXExtractDir, "styles.xml", 165) ;; If Not @Error Then $StylesXMLPath = $XLSXExtractDir & $StylesXMLPath[0] ;; $StylesXML = FileRead($StylesXMLPath) ;; ;ect ect ect ect ;; ;; Local $SheetViews = StringRegExp($WorkSheet, '(?si)<sheetView\s+tabSelected="([^"]*)".*?\sworkbookViewId="([^"]*)".*?\stopLeftCell="([A-Z]{1,3})([0-9]+)".*?\sactiveCell="([A-Z]{1,3})([0-9]+)".*?\sdefaultRowHeight="([^"]*)"', 1) ;; If @Error Then Local $SheetViews[7] ;; $SheetViews[2] = _XLSXSheetGetColumnNumber($SheetViews[2]) ;; $SheetViews[4] = _XLSXSheetGetColumnNumber($SheetViews[4]) ;; ;;;; $SheetViews.... ;; ;;;; $SheetViews[0] = tabSelected ;; ;;;; $SheetViews[1] = workbookViewId ;; ;;;; $SheetViews[2] = top Left Cell - Column Number ;; ;;;; $SheetViews[3] = top Left Cell - Rows Nmmber ;; ;;;; $SheetViews[4] = active Cell - Column Number ;; ;;;; $SheetViews[5] = active Cell - Rows Nmmber ;; ;;;; $SheetViews[6] = default Row Height DirRemove($XLSXExtractDir, 1) Local $nCols = Number($Cols), $nRows = "[0-9]+", $X = StringRegExp($WorkSheet, '(?si)<([^:><]*:?)?worksheet\s+', 1) If Not @Error Then $X = $X[0] If $Rows > 0 Then ;;;; StringRegExp($WorkSheet, '(?s)<' & $X & 'row\s+r="' & $Rows & '".*?</' & $X & 'row>', 1) $nRows = $Rows $Rows = 1 EndIf Local $SheetDimension = StringRegExp($WorkSheet, '(?si)<' & $X & '(?:dimension|autoFilter)\s+ref="([A-Z]{1,3})([0-9]+):([A-Z]{1,3})(?i)([0-9]+)', 1) If Not @Error Then $Cols = _XLSXSheetGetColumnNumber($SheetDimension[2]) If $nRows = "[0-9]+" Then $Rows = $SheetDimension[3] EndIf $SheetDimension = StringRegExp($WorkSheet, '(?si)<' & $X & 'col\s+min="?(\d+)[^>]*></' & $X & 'cols>', 1) If Not @Error And $SheetDimension[0] > $Cols Then $Cols = $SheetDimension[0] If $nRows = "[0-9]+" Then $SheetDimension = StringRegExp($WorkSheet, '(?si).*<' & $X & 'c\s+r="?[A-Z]*(\d+)', 1) If Not @Error And $SheetDimension[0] > $Rows Then $Rows = $SheetDimension[0] EndIf If $nCols > ($Cols + 1) Then Return SetError(5, 0, "") If $Cols < 1 Or $Rows < 1 Or ($Cols * ($Rows + 1)) > 15999999 Then Return SetError(4, 0, "") Local $SheetData = StringRegExp($WorkSheet, '(?s)<' & $X & 'c\s+r="([A-Z]{1,3})(?i)(' & $nRows & ')"\s*(?:s=")?([0-9]*)"?\s*(?:t=")?([^">]*)"?\s*><' & $X & 'v>([^<]*)\s*</' & $X & 'v>\s*</' & $X & 'c>', 3) If @Error Then Return SetError(5, 0, "") If $nCols Then $Cols = 1 Local $SheetDataA[($Rows + 1)][$Cols] = [[UBound($SheetData) - 1]], $ColumnName, $ColumnNumber, $ColumnSize, $SharedStringsXMLSize If $SharedStringsXML Then Local $S = StringRegExp($SharedStringsXML, '(?si)<([^:><]*:?)?sst\s+', 1) If Not @Error Then $S = $S[0] $SharedStringsXML = StringRegExp($SharedStringsXML, '(?si)<' & $S & 'si>(?:<' & $S & 'r>.*?)?<' & $S & 't(?:/|\s[^>]*)?>(.*?)(?:</' & $S & 't>)?(?:</' & $S & 'r>)?</' & $S & 'si>', 3) If Not @Error Then $SharedStringsXMLSize = UBound($SharedStringsXML) For $i = 0 To $SharedStringsXMLSize - 1 If StringInStr($SharedStringsXML[$i], "<", 1) Then $SharedStringsXML[$i] = StringRegExpReplace($SharedStringsXML[$i], '</' & $S & 't>.*?<' & $S & 't>', "") If StringInStr($SharedStringsXML[$i], "&", 1) Then $SharedStringsXML[$i] = StringReplace(StringReplace(StringReplace($SharedStringsXML[$i], "<", "<", 0, 1), ">", ">", 0, 1), "&", "&", 0, 1) Next EndIf EndIf For $i = 0 To $SheetDataA[0][0] Step 5 $ColumnSize = StringLen($SheetData[$i]) - 1 If Not $ColumnSize Then $ColumnNumber = Asc($SheetData[$i]) - 65 Else $ColumnName = StringToASCIIArray($SheetData[$i]) $ColumnNumber = $ColumnName[$ColumnSize] - 65 $ColumnNumber += 26 * ($ColumnName[$ColumnSize - 1] - 64) ;(26 ^ 1) * ($ColumnName[1] - 64) If $ColumnSize > 1 Then $ColumnNumber += 676 * ($ColumnName[0] - 64) ;(26 ^ 2) * ($ColumnName[0] - 64) ;;;$ColumnNumber = _XLSXSheetGetColumnNumber($SheetData[$i], 1) EndIf If $nCols Then If $nCols <> ($ColumnNumber + 1) Then ContinueLoop $ColumnNumber = 0 EndIf If $Rows = 1 Then $SheetData[$i + 1] = 1 If $SheetData[$i + 3] = "s" And $SharedStringsXMLSize > $SheetData[$i + 4] Then $SheetDataA[$SheetData[$i + 1]][$ColumnNumber] = $SharedStringsXML[$SheetData[$i + 4]] ElseIf $SheetData[$i + 2] = 2 Then $SheetDataA[$SheetData[$i + 1]][$ColumnNumber] = _SSNToDate($SheetData[$i + 4]) Else $SheetDataA[$SheetData[$i + 1]][$ColumnNumber] = $SheetData[$i + 4] EndIf Next $SheetDataA[0][0] = $Rows If $iFlag Then $HyperLinks = StringRegExp($WorkSheet, '(?si)<' & $X & 'hyperlink\s+ref="([A-Z]{1,3})(?i)(' & $nRows & ')".*?\s+display="([^"]*)"', 3) ;;$HyperLinks = StringRegExp($WorkSheet, '(?si)<' & $X & 'hyperlink\s+ref="([A-Z]{1,3})(?i)' & $nRows & '"\s+r:id="([^"]*)"\s+display="([^"]*)"', 3) If Not @Error Then Local $HyperLinksSize = UBound($HyperLinks) - 1 For $i = 0 To $HyperLinksSize Step 3 $ColumnNumber = _XLSXSheetGetColumnNumber($HyperLinks[$i], 1) If $Rows = 1 Then $HyperLinks[$i + 1] = 1 $SheetDataA[$HyperLinks[$i + 1]][$ColumnNumber] &= @LF & $HyperLinks[$i + 2] Next EndIf EndIf If $nCols And $Rows = 1 Then Return SetError(0, $SheetDataA[1][0] = "", $SheetDataA[1][0]) Return SetError(0, UBound($SheetDataA, 2), $SheetDataA) EndFunc ;==>_XLSXReadToArray ; #FUNCTION# ================================================================================================================= ; Name...........: _XLSXSheetGetColumnNumber ; Description ...: The _XLSXSheetGetColumnNumber Fuction return Column Number of EXCEL XLSX Sheet ; Syntax.........: _XLSXSheetGetColumnNumber($ColumnName) ; Parameters ....: $ColumnName - [A-Z] Uppercase Caracter\String, are not Supported line with more than 3 characters ; $iFlag - Optional ; |$iFlag = 0 (Default) Column Number ; |$iFlag = 1 Column Number - 1 (for Array Index 0) ; Return values .: Success - Return Column Number ; Failure - @Error ; Author ........: DXRW4E ; Modified.......: ; Remarks .......: Limit is 18278 (A = 1 & AB = 27 & ZZZ = 18278) ; Related .......: ; Link ..........: ; Example .......: _XLSXSheetGetColumnNumber("ABC") ; Note ..........: ; ============================================================================================================================ Func _XLSXSheetGetColumnNumber($ColumnName, $iFlag = 0) If Not StringRegExp($ColumnName, '^[A-Z]{1,3}$') Or $iFlag < 0 Or $iFlag > 1 Then Return SetError(1, 0, 0) Local $ColumnNumber, $SheetDimension = StringLen($ColumnName) - 1 If Not $SheetDimension Then $ColumnNumber = Asc($ColumnName) - 64 - $iFlag Else $ColumnName = StringToASCIIArray($ColumnName) $ColumnNumber = $ColumnName[$SheetDimension] - 64 - $iFlag $ColumnNumber += 26 * ($ColumnName[$SheetDimension - 1] - 64) ;(26 ^ 1) * ($ColumnName[1] - 64) If $SheetDimension > 1 Then $ColumnNumber += 676 * ($ColumnName[0] - 64) ;(26 ^ 2) * ($ColumnName[0] - 64) EndIf Return $ColumnNumber EndFunc ;==>_XLSXSheetGetColumnNumber ; #FUNCTION# ================================================================================================================= ; Name...........: _SSNToDate ; Description ...: The _SSNToDate Fuction return Date from sequential serial number ; Syntax.........: _SSNToDate($iDay) ; Parameters ....: $iDay - sequential serial number (generated from DATE fuction on EXCEL, example 39637 = 7/8/2008) ; Return values .: Success - Return DATE ; Failure - @Error ; Author ........: DXRW4E ; Modified.......: ; Remarks .......: DATE String is Month/Day/Year, Year - is number is 1900 to 9999 ; Related .......: ; Link ..........: ; Example .......: _SSNToDate(39637) ; Note ..........: ; ============================================================================================================================ Func _SSNToDate($iDay) If $iDay < 1 Or $iDay > 2958465 Then Return SetError(1, 0, "") $DateSSN[0] = Int($iDay / 365) $DateSSN[25] = $DateSSN[0] / 4 $DateSSN[26] = IsFloat($DateSSN[25]) $iDay = $iDay - ($DateSSN[0] * 365) - Int($DateSSN[25]) - $DateSSN[26] If $iDay < 1 Then $DateSSN[0] -= 1 $DateSSN[25] = IsInt(($DateSSN[0] -1) / 4) $iDay += 365 + $DateSSN[25] $DateSSN[26] = Int($DateSSN[25] = 0) EndIf $DateSSN[2] -= $DateSSN[26] For $iMonth = 1 To 11 If $DateSSN[$iMonth] >= $iDay Then ExitLoop $iDay -= $DateSSN[$iMonth] Next $DateSSN[2] += $DateSSN[26] Return $iMonth & "/" & $iDay & "/" & (1900 + $DateSSN[0]) EndFunc ;==>_SSNToDate ; #FUNCTION# ================================================================================================================= ; Name...........: _DateToSSN ; Description ...: The _DateToSSN Fuction return sequential serial number that represent a particular Date ; Syntax.........: _DateToSSN($iYear, $iMonth, $iDay) ; Parameters ....: $iYear - Year - is number is 1900 to 9999 ; Required. The value of the year argument can include one to four digits. Excel interprets the year argument ; according to the date system your computer is using. By default, Microsoft Excel for Windows uses the 1900 date system. ; We recommend using four digits for the year argument to prevent unwanted results. For example, "07" could mean "1907" or "2007." Four digit years prevent confusion. ; If year is between 0 (zero) and 1899 (inclusive), Excel adds that value to 1900 to calculate the year. For example, DATE(108,1,2) returns January 2, 2008 (1900+108). ; If year is between 1900 and 9999 (inclusive), Excel uses that value as the year. For example, _DateToSSN((2008,1,2) returns January 2, 2008. ; If year is less than 0 or is 10000 or greater, _DateToSSN returns the @Error ; $iMonth - is number is 1 to 12, If Month is less than 0 or is 13 or greater, _DateToSSN returns the @Error ; $iDay - Required. A positive or negative integer representing the day of the month from 1 to 31. ; If day is greater than the number of days in the month specified, day adds that number of days to the first day in the month. ; For example, _DateToSSN(2008,1,35) returns the serial number representing February 4, 2008. ; If day is less than 1, day subtracts the magnitude that number of days, plus one, from the first day of the month specified. ; For example, _DateToSSN(2008,1,-15) returns the serial number representing December 16, 2007. ; Return values .: Success - Return Sequential Serial Number ; Failure - @Error ; Author ........: DXRW4E ; Modified.......: ; Remarks .......: Sequential Serial Number, _DateToSSN(2008, 7, 8) Return 39637, that represent 7/8/2008 ; ; NOTE - Excel stores dates as sequential serial numbers so that they can be used in calculations. January 1, 1900 is serial number 1, ; and January 1, 2008 is serial number 39448 because it is 39,447 days after January 1, 1900. ; ; _DateToSSN NOT SUPPORT FOR NOW, THIS ; $iMonth Required. A positive or negative integer representing the month of the year from 1 to 12 (January to December). ; If month is greater than 12, month adds that number of months to the first month in the year specified. For example, ; DATE(2008,14,2) returns the serial number representing February 2, 2009. ; If month is less than 1, month subtracts the magnitude of that number of months, plus 1, from the first month in the ; year specified. For example, DATE(2008,-3,2) returns the serial number representing September 2, 2007. ; Related .......: ; Link ..........: ; Example .......: _DateToSSN(39637) ; Note ..........: ; ============================================================================================================================ Func _DateToSSN($iYear, $iMonth, $iDay) If $iYear < 1900 Or $iYear > 9999 Or $iMonth < 1 Or $iMonth > 12 Then Return SetError(1, 0, "") $iYear -= 1900 $DateSSN[0] = $iYear / 4 If IsFloat($DateSSN[0]) And $iMonth < 3 Then $iDay += 1 Return ($iYear * 365) + Int($DateSSN[0]) + $DateSSN[$iMonth + 12] + $iDay EndFunc ;==>_DateToSSN ; #FUNCTION# ======================================================================================================================================================= ; Name...........: _FileListToArrayEx ; Description ...: Lists files and\or folders in a specified path (Similar to using Dir with the /B Switch) ; Syntax.........: _FileListToArrayEx($sPath[, $sFilter = "*"[, $iFlag = 0]]) ; Parameters ....: $sPath - Path to generate filelist for. ; $sFilter - Optional the filter to use, default is *. (Multiple filter groups such as "All "*.png|*.jpg|*.bmp") Search the Autoit3 helpfile for the word "WildCards" For details. ; $iFlag - Optional: specifies whether to return files folders or both Or Full Path (add the flags together for multiple operations): ; |$iFlag = 0 (Default) Return both files and folders ; |$iFlag = 1 Return files only ; |$iFlag = 2 Return Folders only ; |$iFlag = 4 Search SubDirectory ; |$iFlag = 8 Return Full Path ; |$iFlag = 16 $sFilter do Case-Sensitive matching (By Default $sFilter do Case-Insensitive matching) ; |$iFlag = 32 Disable the return the count in the first element - effectively makes the array 0-based (must use UBound() to get the size in this case). ; By Default the first element ($array[0]) contains the number of file found, the remaining elements ($array[1], $array[2], etc.) ; |$iFlag = 64 $sFilter is REGEXP Mod, See Pattern Parameters in StringRegExp (Can not be combined with flag 16) ; |$iFlag = 128 Return Backslash at the beginning of the file name, example Return "\Filename1.xxx" (Can not be combined with flag 8) ; Return values .: Failure - @Error ; |1 = Path not found or invalid ; |2 = Invalid $sFilter ; |3 = No File(s) Found ; Author ........: DXRW4E ; Modified.......: ; Remarks .......: The array returned is one-dimensional and is made up as follows: ; $array[0] = Number of Files\Folders returned ; $array[1] = 1st File\Folder ; $array[2] = 2nd File\Folder ; $array[3] = 3rd File\Folder ; $array[n] = nth File\Folder ; Related .......: ; Link ..........: ; Example .......: Yes ; Note ..........: Special Thanks to SolidSnake & Tlem ; ================================================================================================================================================================== Func _FileListToArrayEx($sPath, $sFilter = "*", $iFlag = 0) $sPath = StringRegExpReplace($sPath & "\", "[\\/]+", "\\") If Not FileExists($sPath) Then Return SetError(1, 1, "") If StringRegExp($sFilter, StringReplace('^\s*$|\v|[\\/:><"]|^\||\|\||\|$', "[" & Chr(BitAND($iFlag, 64) + 28) & '\/:><"]|^\||\|\||\|$', "\\\\")) Then Return SetError(2, 2, "") Local $hSearch, $sFile, $sFileList, $sSubDir = BitAND($iFlag, 4), $sDelim = "|", $sDirFilter = StringReplace($sFilter, "*", "") $hSearch = FileFindFirstFile($sPath & "*") If @Error Then Return SetError(3, 3, "") Local $hWSearch = $hSearch, $hWSTMP, $SearchWD, $Extended, $iFlags = StringReplace(BitAND($iFlag, 1) + BitAND($iFlag, 2), "3", "0") If BitAND($iFlag, 8) Then $sDelim &= $sPath If BitAND($iFlag, 128) Then $sDelim = "|\" If Not BitAND($iFlag, 64) Then $sFilter = StringRegExpReplace(BitAND($iFlag, 16) & "(?i)(", "16\(\?\i\)|\d+", "") & StringRegExpReplace(StringRegExpReplace(StringRegExpReplace(StringRegExpReplace($sFilter, "[^*?|]+", "\\Q$0\\E"), "\\E(?=\||$)", "$0\$"), "(?<=^|\|)\\Q", "^$0"), "\*+", ".*") & ")" While 1 $sFile = FileFindNextFile($hWSearch) If @Error Then If $hWSearch = $hSearch Then ExitLoop FileClose($hWSearch) $hWSearch -= 1 $SearchWD = StringLeft($SearchWD, StringInStr(StringTrimRight($SearchWD, 1), "\", 1, -1)) ElseIf $sSubDir Then $Extended = @Extended If ($iFlags + $Extended <> 2) Then If $sDirFilter Then If StringRegExp($sFile, $sFilter) Then $sFileList &= $sDelim & $SearchWD & $sFile Else $sFileList &= $sDelim & $SearchWD & $sFile EndIf EndIf If Not $Extended Then ContinueLoop $hWSTMP = FileFindFirstFile($sPath & $SearchWD & $sFile & "\*") If $hWSTMP = -1 Then ContinueLoop $hWSearch = $hWSTMP $SearchWD &= $sFile & "\" Else If ($iFlags + @Extended = 2) Or StringRegExp($sFile, $sFilter) = 0 Then ContinueLoop $sFileList &= $sDelim & $sFile EndIf WEnd FileClose($hSearch) If Not $sFileList Then Return SetError(3, 3, "") Return StringSplit(StringTrimLeft($sFileList, 1), "|", StringReplace(BitAND($iFlag, 32), "32", 2)) EndFunc ;==>_FileListToArrayEx Func _XLSXZip_COMErrorFunc() Return SetError(1, 0, "") EndFunc ;==>_XLSXZip_COMErrorFunc example #include <Array.au3> #include <_XLSXReadToArray.au3> local $a, $t, $Error, $Extended $t = TimerInit() InetGet("http://go.microsoft.com/fwlink/?LinkID=245778", @WindowsDir & "\Temp\BulletinSearch.xlsx") $a = _XLSXReadToArray(@WindowsDir & "\Temp\BulletinSearch.xlsx", 0, 0, 0) $t = TimerDiff($t) _ArrayDisplay($a, $t) ;;or $t = TimerInit() $a = _XLSXReadToArray(@WindowsDir & "\Temp\BulletinSearch.xlsx", 0, 2, 11) $Error = @Error $Extended = @Extended $t = TimerDiff($t) ConsoleWrite("Timer = " & $t & @LF) ConsoleWrite("Return = " & $a & " - $Error = " & $Error & " - $Extended = " & $Extended & @LF) exit _XLSXReadToArray.au3
- 23 replies
-
- _xlsxreadtoarray
- _filelisttoarrayex
-
(and 3 more)
Tagged with:
-
I have a spreadsheet - daily routine which has two columns: activity and time as shown here | Activity | Time | |----------------------|----------| | Sleep | 6:00 am | | Toilet | 6:15 am | | Get ready for gym | 6:30 am | | Exercise | 7:50 am | | ... more things | 9:00 pm | | ... still more | 10:45 pm | | Sleep | 6:00 am | I wanted to find out, say in C1 which activity is current for me using now() I.e., if it’s 6:45am on my watch, it should show me Exercise in C1 Thanks to Adam D. PE, this formula works like magic to get the result =VLOOKUP(MOD(NOW(),1),{B2:B,A2:A},2,1) Now, I want to reproduce same result in autoit, how to do that? To have easy solution say, I copy-paste spreadsheet data in array directly in code, right? Use for loop and run the above vlookup function and show the answer using tooltip. How to achieve this? please help.
-
- vlookup
- spreadsheet
-
(and 3 more)
Tagged with:
-
I have an Autoit script that lists files from a folder into an array list. Is there a way to separate the filenames by an underscore and include the id, version, name and date into separate columns in Excel. Example of filename: 12345_v1.0_TEST Name [12345]_01.01.2022.html 12345 would be in one column v1.0 would be in another column TEST Name [12345] would be in another column 01.01.2022 would be in another column .html would be in another column Note: filenames always change each day. Here is my code that lists the files into column C and then writes the column Headers into Column D, E, F, G. Just need some help with separating them into columns by the _ delimiter
-
Usually when I collect data from DataBase I need to give EndUser a possibility to select rows which should be taken in the processing loop. I was searching on the forum and I'm not able to find any UDF or even example of how to select data from array. I have my own solutions but I think they are not worth posting on the forum as it is very old code and I am looking for a better solution. Could anybody point me to some examples/solutions ? Thank you in advance. @mLipok
-
I have a string containing the full path of an executable and an array of executables without their paths. I am trying to compare the string to the list in the array and if a match is found, remove it from the array. The entry get removed from the array successfully, and after checking its return result, uses it to update the ubound if it succeeded, but it doesn't want to update to the new value. Any ideas what I am doing wrong? It acts like it is read-only. #include <Array.au3> #include <File.au3> Local $sApp_Exe = "F:\App\Nextcloud\nextcloud.exe" Local $aWaitForEXEX = [3, "Nextcloud.exe", "nextcloudcmd.exe", "QtWebEngineProcess.exe"] For $h = 1 To $aWaitForEXEX[0] If StringInStr($sApp_Exe, $aWaitForEXEX[$h]) <> 0 Then $iRet = _ArrayDelete($aWaitForEXEX, $h) If $iRet <> -1 Then $aWaitForEXEX[0] = $iRet ;this line doesn't work. $aWaitForEXEX[0] doesn't update and shortly gives Error: Array variable has incorrect number of subscripts or subscript dimension range exceeded.: _ArrayDisplay($aWaitForEXEX) EndIf Next
-
#Include <Array.au3> #include <Constants.au3> $s = FileRead("2.txt") Local $w = StringRegExp($s, '(?is)(\b\w+\b)(?!.*\b\1\b)', 3) _ArrayColInsert($w, 1) For $i = 0 to UBound($w)-1 StringRegExpReplace($s, '(?i)\b' & $w[$i][0] & '\b', $w[$i][0]) $w[$i][1] = @extended Next _ArraySort($w, 1, 0, 0, 1) _ArrayDisplay($w) i have this script that returns 3 columns i need to copy the Col 0 and Col 1 as text to paste on notepad or excel you will have to create a "copy" button if possible array.au3 2.txt
-
I have a dataset like this, (a strubg) Username: User1 Type: Admin RegDate: 1999 Username: User2 Type: User RegDate: 2000 How to make a 2 dimensional array that I can display with _ArrayDisplay? This would be a perfect 2D array to represent my data: Username Tpye RegDate User1 Admin 1999 User2 User 2000 If you run this Powershell this powershell command, you can get this dataset that I am talking about: Get-LocalUser | Select * With this code you can try it to read into a string: #include <GuiConstantsEx.au3> #include <WindowsConstants.au3> #include "GUIListViewEx.au3" #include <Array.au3> ; Just for display in example #RequireAdmin #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_UseX64=y #EndRegion $sCommand = "powershell.exe Get-LocalUser | Select *" Local $iPid = Run($sCommand, @WorkingDir , @SW_SHOW , $STDOUT_CHILD) ProcessWaitClose($iPid) Local $sOutput = StdoutRead($iPID) ConsoleWrite($sOutput) How can I correctly split $sOutput into a 2D array (with the above mentioned layout) that I can display and I work with?
-
Hi guys, talking about array in array, I would like to directly assign a value to an element in an array contained in another array. While it is quite simple to access the value if it is already setted: Local $a[3] = [1, 2], $b[2] = [3, 4] $a[2] = $b ConsoleWrite(($a[2])[0] & " " & ($a[2])[1] & @CRLF) If I try to write directly to the element, I get an error: Local $a[3] = [1, 2] Local $b[2] $a[2] = $b ($a[2])[0] = 1 Is assigning first every value of the contained array and then including it in the container the only way?
-
$sCommands1 = 'powershell.exe Get-ChildItem' $iPid = run($sCommands1 , @WorkingDir , @SW_SHOW , 0x2) $sOutput = "" While 1 $sOutput &= StdoutRead($iPID) If @error Then ExitLoop EndIf WEnd ;~ msgbox(0, '' , $sOutput) ConsoleWrite("$sOutput") ConsoleWrite($sOutput) ConsoleWrite(@CRLF) $aOutput = stringsplit($sOutput ,@LF , 2) For $i=0 To UBound($aOutput) - 1 Step 1 ConsoleWrite($aOutput[$i]) Next The script above reads the whole directory into a one dimensional array, but I need to work with the array, so I need to split the array into multiple dimensions. I have already read some forum answers here, and I have already tried these commands: Are there any way to use the $aOutput variable like in PowerShell: PowerShell: $a = Get-ChildItem $a.Mode I imagine this in AutoIt $aOutput ConsoleWrite($aOutput[i].Mode) Or if I split this command into 2 dimension like: For $i To UBound($aOutput)-1 Step 1 ConsoleWrite($aOutput[$i][1]) ConsoleWrite($aOutput[$i][2]) Next
- 6 replies
-
- powershell
- solved
-
(and 1 more)
Tagged with:
-
Please Help With 3D Arrays "[Solved]"
Mannyfresh31 posted a topic in AutoIt General Help and Support
Please help with this 3D Array the first example works the secound doesn't. Need help to understand how Arrays work. Many thanks in advance ;First Example Dim $aArray[2][2][2] $aArray[0][0][0] = 1 $aArray[0][0][1] = 2 $aArray[0][1][0] = 3 $aArray[0][1][1] = 4 $aArray[1][0][0] = 5 $aArray[1][0][1] = 6 $aArray[1][1][0] = 7 $aArray[1][1][1] = 8 For $a = 0 to 1 for $b = 0 to 1 for $c = 0 to 1 ConsoleWrite($aArray[$a][$b][$c] & @CRLF) Next Next Next ;Secound Example Local $aArraym [2][2][2]=[[[1,2,],[3,4],[5,6],[7,8]]] For $a = 0 to 1 for $b = 0 to 1 for $c = 0 to 1 ConsoleWrite($aArraym[$a][$b][$c] & @CRLF) Next Next Next -
My solution is to write nested arrays without copying. The problem was described hier. Function: #include <Array.au3> ; #FUNCTION# ==================================================================================================================== ; Name ..........: _ArrayNestedSet ; Description ...: Assigns a value to an element of a nested 1D array. ; Syntax ........: _ArrayNestedSet(ByRef $aArray, $vIndex, $vValue) ; Parameters ....: $aArray - an array of arrays. ; $vIndex - an index or 1d-array of indexes; ; a size if $vValue not defined (zero to delete). ; $vValue - a value (create, resize or delete if not defined). ; ; Return values .: on success - 1 ; @extended - nesting level of operation ; on failure - 0 ; @extended - nesting level of error ; @error = 1 - invalid array ; @error = 2 - invalid index ; Author ........: ; Modified ......: kovlad ; Remarks .......: ; Related .......: ; Link ..........: https://www.autoitscript.com/forum/topic/185638-assign-a-value-to-an-array-in-array-element/ ; https://www.autoitscript.com/trac/autoit/ticket/3515?replyto=description ; Example .......: Yes ; =============================================================================================================================== Func _ArrayNestedSet(ByRef $aArray, $vIndex, $vValue = Default) Local $extended = @extended + 1 If IsArray($vIndex) Then If UBound($vIndex, 0) <> 1 Then _ Return SetError(2, $extended) If UBound($vIndex) > 1 Then If UBound($aArray, 0) <> 1 Then _ Return SetError(1, $extended) ; keep index for this array Local $i = $vIndex[0] If $i < 0 Or UBound($aArray) <= $i Then _ Return SetError(2, $extended) ; delete index of this array _ArrayDelete($vIndex, 0) ; recursive function call Local $return = _ArrayNestedSet($aArray[$i], $vIndex, $vValue) If @error Then Return SetError(@error, @extended + 1, 0) Else Return SetExtended(@extended + 1, 1) EndIf Else $vIndex = $vIndex[0] EndIf EndIf If $vValue = Default Then If $vIndex < 0 Then _ Return SetError(2, $extended) If $vIndex = 0 Then ; delete array and free memory $aArray = 0 Return SetExtended($extended, 1) EndIf If UBound($aArray, 0) = 1 Then ; resize array keeping data ReDim $aArray[$vIndex] Return SetExtended($extended, 1) Else ; create new nested array Local $aTmp[$vIndex] $aArray = $aTmp Return SetExtended($extended, 1) EndIf Else If UBound($aArray) <= $vIndex Then _ Return SetError(2, $extended + 1) ; set value of array entry $aArray[$vIndex] = $vValue Return SetExtended($extended, 1) EndIf EndFunc Examples: ; write value to 1st nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : write value to 1st nested array" & @CRLF) Local $aTmp1[4] = [1,2,3,4] _ArrayDisplay($aTmp1, "$aTmp1") Local $aArray[2] = [$aTmp1] ConsoleWrite( _ "_ArrayNestedSet($aArray[0], 3, 14) = " & _ArrayNestedSet($aArray[0], 3, 14) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay($aArray[0], "$aArray[0]") ; resize 1st nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : resize 1st nested array" & @CRLF) ConsoleWrite( _ "_ArrayNestedSet($aArray[0], 8) = " & _ArrayNestedSet($aArray[0], 8) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay($aArray[0], "$aArray[0]") ; write array to 1st nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : write array to 1st nested array" & @CRLF) Local $aTmp11[4] = [11,12,13,14] _ArrayDisplay($aTmp11, "$aTmp11") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], 2, $aTmp11) = " & _ArrayNestedSet($aArray[0], 2, $aTmp11) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay(($aArray[0])[2], "($aArray[0])[2]") ; write value to 2nd nested array using index array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : write value to 2nd nested array using index array" & @CRLF) Local $aIndex1[2] = [2,3] _ArrayDisplay($aIndex1, "$aIndex1") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex1, 140) = " & _ArrayNestedSet($aArray[0], $aIndex1, 140) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay(($aArray[0])[2], "($aArray[0])[2]") ; resize 2nd nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : resize 2nd nested array" & @CRLF) Local $aIndex1[2] = [2,8] _ArrayDisplay($aIndex1, "$aIndex1") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex1) = " & _ArrayNestedSet($aArray[0], $aIndex1) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay(($aArray[0])[2], "($aArray[0])[2]") ; create new 3rd nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : create new 3rd nested array" & @CRLF) Local $aIndex2[3] = [2,7,6] _ArrayDisplay($aIndex2, "$aIndex2") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex2) = " & _ArrayNestedSet($aArray[0], $aIndex2) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF & @CRLF) _ArrayDisplay((($aArray[0])[2])[7], ")($aArray[0])[2])[7]") ; delete 3rd nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : delete 3rd nested array" & @CRLF) Local $aIndex3[3] = [2,7,0] _ArrayDisplay($aIndex3, "$aIndex2") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex3) = " & _ArrayNestedSet($aArray[0], $aIndex3) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF) ConsoleWrite("IsArray((($aArray[0])[2])[7]) = " & IsArray((($aArray[0])[2])[7]) & @CRLF & @CRLF) ; write 0 in 1st nested array to delete the 2nd nested array ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : write 0 in 1st nested array to delete the 2nd nested array" & @CRLF) Local $aIndex4[1] = [2] _ArrayDisplay($aIndex4, "$aIndex4") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex4, 0) = " & _ArrayNestedSet($aArray[0], $aIndex4, 0) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF) ConsoleWrite("IsArray(($aArray[0])[2]) = " & IsArray(($aArray[0])[2]) & @CRLF & @CRLF) ; delete 1st nested array (same as '$aArray[0] = 0') ConsoleWrite("@@ Debug(" & @ScriptLineNumber & ") : delete 1st nested array (same as '$aArray[0] = 0')" & @CRLF) Local $aIndex5[1] = [0] _ArrayDisplay($aIndex5, "$aIndex5") ConsoleWrite( _ "_ArrayNestedSet($aArray[0], $aIndex5) = " & _ArrayNestedSet($aArray[0], $aIndex5) & @CRLF & _ " @error = " & @error & @CRLF & _ " @extended = " & @extended & @CRLF) ConsoleWrite("IsArray($aArray[0]) = " & IsArray($aArray[0]) & @CRLF & @CRLF)
-
My _Excel_RangeCopyPaste is not working as intended. What I am trying to accomplish is copy the range B:E using _Excel_RangeCopyPaste in the first row and repeat the same for row 2 and so on. ;Skip from reading header columns Local $Skipline = 0 ;0==> first line Local $temprf For $i = 0 To UBound($aArray2) - 1 If $Skipline = $i Then ContinueLoop $temprf &= $aArray2[$i] _Excel_RangeCopyPaste($oWorkbook.Activesheet, $oRange) Local $oTest = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "PasteButton") ;This button will paste values from the Clipboard once clicked _WD_ElementAction($sSession, $oTest, 'click')) Next Here's the full code: #Include <Chrome.au3> #Include <wd_core.au3> #Include <wd_helper.au3> #Include <WinHttp.au3> #include <MsgBoxConstants.au3> #include <IE.au3> #include <Array.au3> #include <Excel.au3> Local $sDesiredCapabilities, $sSession SetupChrome() _WD_Startup() $sSession = _WD_CreateSession($sDesiredCapabilities) _WD_LoadWait($sSession) _WD_Navigate($sSession, "test.html") Local $oAppl = _Excel_Open() Local $sWorkbook = "test.xlsx" Local $oWorkbook = _Excel_BookOpen($oAppl, $sWorkbook) ;open excel and pass both parameters Local $aArray2 = _Excel_RangeRead($oWorkbook,Default,$oWorkbook.ActiveSheet.Usedrange.Columns("A:A")) Local $oRange = $oWorkbook.ActiveSheet.Range("B:E") ;Skip from reading header columns Local $Skipline = 0 ;0==> first line Local $temprf For $i = 0 To UBound($aArray2) - 1 If $Skipline = $i Then ContinueLoop $temprf &= $aArray2[$i] _Excel_RangeCopyPaste($oWorkbook.Activesheet, $oRange) Local $oTest = _WD_FindElement($sSession, $_WD_LOCATOR_ByCSSSelector, "PasteButton") ;This button will paste values from the Clipboard once clicked _WD_ElementAction($sSession, $oTest, 'click')) Next _WD_Shutdown() Func SetupChrome() _WD_Option('Driver', 'chromedriver.exe') _WD_Option('Port', 9515) _WD_Option('DriverParams', '--log-path="' & @ScriptDir & '\chrome.log"') Return '{"capabilities":{"alwaysMatch":{"goog:chromeOptions":{"w3c":true,' & _ '"excludeSwitches":["enable-automation"],"useAutomationExtension":false}}}}' EndFunc ;==>SetupChrome For the first row I am trying to copy just B:E with the following info Apple Banana Orange Mango and then repeat for row 2, row 3, etc. I've attached the spreadhseet. test.xlsxI have also attached the excel file for reference.
- 5 replies
-
- _excel_rangecopypaste
- excel
-
(and 1 more)
Tagged with: