: bharatvaj/lobasic-macros

LibreOffice macros I use often

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
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 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378 
379 
380 
381 
382 
383 
384 
385 
386 
387 
388 
389 
390 
391 
392 
393 
394 
395 
396 
397 
398 
399 
400 
401 
402 
403 
404 
405 
406 
407 
408 
409 
410 
411 
412 
413 
414 
415 
416 
417 
418 
419 
420 
421 
422 
423 
424 
425 
426 
427 
428 
429 
430 
431 
432 
433 
434 
435 
436 
437 
438 
439 
440 
441 
442 
443 
444 
445 
446 
447 
448 
449 
450 
451 
452 
453 
454 
455 
456 
457 
458 
459 
460 
461 
462 
463 
464 
465 
466 
467 
468 
469 
470 
471 
472 
473 
474 
475 
476 
477 
478 
479 
480 
481 
482 
483 
484 
485 
486 
487 
488 
489 
490 
491 
492 
493 
494 
495 
496 
497 
498 
499 
500 
501 
502 
503 
504 
505 
506 
507 
508 
509 
510 
511 
512 
513 
514 
515 
516 
517 
518 
519 
520 
521 
522 
523 
524 
525 
526 
527 
528 
529 
530 
531 
532 
533 
534 
535 
536 
537 
538 
539 
540 
541 
542 
543 
544 
545 
546 
547 
548 
549 
550 
551 
552 
553 
554 
555 
556 
557 
558 
559 
560 
561 
562 
563 
564 
565 
566 
567 
568 
569 
570 
571 
572 
573 
574 
575 
576 
577 
578 
579 
580 
581 
582 
583 
584 
585 
586 
587 
588 
589 
590 
591 
592 
593 
594 
595 
596 
597 
598 
599 
600 
601 
602 
603 
604 
605 
606 
607 
608 
609 
610 
611 
612 
613 
614 
615 
616 
617 
618 
619 
620 
621 
622 
623 
624 
625 
626 
627 
628 
629 
630 
631 
632 
633 
634 
635 
636 
637 
638 
639 
640 
641 
642 
643 
644 
645 
646 
647 
648 
649 
650 
651 
652 
653 
654 
655 
656 
657 
658 
659 
660 
661 
662 
663 
664 
665 
666 
667 
668 
669 
670 
671 
672 
673 
674 
675 
676 
677 
678 
679 
680 
681 
682 
683 
684 
685 
686 
687 
688 
689 
690 
691 
692 
693 
694 
695 
696 
697 
698 
699 
700 
701 
702 
703 
704 
705 
706 
707 
708 
709 
710 
711 
712 
713 
714 
715 
716 
717 
718 
719 
720 
721 
722 
723 
724 
725 
726 
727 
728 
729 
730 
731 
732 
733 
734 
735 
736 
737 
738 
739 
740 
741 
742 
743 
744 
745 
746 
747 
748 
749 
750 
751 
752 
753 
754 
755 
756 
757 
758 
759 
760 
761 
762 
763 
764 
765 
766 
767 
768 
769 
770 
771 
772 
773 
774 
775 
776 
777 
778 
779 
780 
781 
782 
783 
784 
785 
786 
787 
788 
789 
790 
791 
792 
793 
794 
795 
796 
797 
798 
799 
800 
801 
802 
803 
804 
805 
806 
807 
808 
809 
810 
811 
812 
813 
814 
815 
816 
817 
818 
819 
820 
821 
822 
REM  *****  BASIC  *****
Option Explicit

Const FieldOperationLimit = 10

Type SondageOperation
	OpName as String
	OpLocation as String
End Type

Type SondageStatement
	Cond as Integer
	Operand as String
	OpIds() as Integer
End Type

Type SondageField
		Field as String
		ImportFormat as Integer
		Width as Long
		Statements() as SondageStatement
		Values() as String
End Type

Type SondageReport
	Title as String
	Settings() as com.sun.star.PropertyValue
	Fields() as SondageField
End Type

Type SondageConfiguration
	Reports() as SondageReport
	Headers() as String
End Type

' FIXME Remove the 100 hard limit later
Dim OperationTable(100) as SondageOperation
Dim OperationTableLen%

Function ColorRow(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function ColumnOperation(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function ColorCell(ByRef oSheet as Object, oRanges as Variant, highlightColor as Variant)
	Dim oRange
	For oRange = LBound(oRanges) To UBound(oRanges)
		oRange.CellBackColor = highlightColor
	Next
End Function

Function Delete(ByRef oSheet as Object, oRanges as Variant, sArgs() as String)
	Dim oRange
	For Each oRange In oRanges
		oSheet.removeByIndex(oRange.RangeAddress.StartRow)
	Next oRange
End Function

Sub SondageRegisterFunction(macroLocation$, macroName$)
	OperationTable(OperationTableLen).OpLocation = macroLocation
	OperationTable(OperationTableLen).OpName = macroName
	OperationTableLen = OperationTableLen + 1
End Sub

Function _ReadUntilEndOrCharacter(ByRef sCell$, startIndex%, expect$, ByRef endIndex as Variant) as String
	Dim c$, i%
	c = Left(sCell, startIndex)

	For i = startIndex To Len(sCell)
		If c = expect Then
			_ReadUntilEndOrCharacter = Mid(sCell, startIndex,  i - startIndex - 1)
			endIndex = i
			Exit Function
		End If

		If c = "\n" Or c = ";" Then
			ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'"
			Exit Function
		End If
		c = Mid(sCell, i, 1)
	Next
	_ReadUntilEndOrCharacter = Mid(sCell, startIndex,  i - startIndex)
	endIndex = i - 1
End Function

Function _ReadUntilCharacters(ByRef sCell$, startIndex%, expects() as Variant, ByRef endIndex&) as String
	Dim c$, expect$

	For endIndex = startIndex To Len(sCell)
		c = Mid(sCell, endIndex, 1)
		For Each expect In expects
			If c = expect Then
				_ReadUntilCharacters = Mid(sCell, startIndex,  endIndex - startIndex)
				Exit Function
			End If
			If c = "\n" Or c = ";" Then
				ErrorLocal$ = "Expected '" & expect & "' got '" & c & "'"
				Exit Function
			End If
		Next
	Next
	ErrorLocal$ = "Expected '" & expect & "' but reached end of cell"
End Function

Sub TestSub
	Dim sCell$, colName$
	Dim iCell%
	sCell = "${variable with space} " & CHR(34) & "quoted string" & CHR(34)
	colName = _ReadUntilCharacters(sCell, 3, Array("}"), iCell)
	Print colName
	If ErrorLocal$ <> "" Then
		Print "Some error occurred: " & ErrorLocal
		Exit Sub
	End If
	colName = _ReadUntilCharacters(sCell, iCell +3 , Array(CHR(34)), iCell)
	If ErrorLocal$ <> "" Then
		Print "Some error occurred: " & ErrorLocal
		Exit Sub
	End If
	Print colName
	'If ErrorLocal$ <> "" Then
	'	Print "Some error occurred: " & ErrorLocal
	'	Exit Sub
	'End If
End Sub

Function FunctionCall(colName$, actions)
	Dim action$
	For Each action in actions
		Print colName & " acts on " & action
	Next 'action
End Function

Function TokenDriver(Optional sCell)
	Dim sonVars: sonVars = SondageReadSettings()
	Dim si%: si = 1
	Dim tok$
	Dim tokType$ 'mode
	If IsMissing(sCell) Then sCell = "${OrgCode}_Portln then @Area(.BadStyle @SomeOther Sort-ASCENDING)"
	sCell = SondageExpandVariables(sCell, sonVars)

	Dim sCellLen: sCellLen = Len(sCell)
	tok = GetToken(sCell, si, tokType)
	While tok <> ""
			Select Case tokType
				Case "@"
					Print "Some column types: "& tok
				Case "("
					Print "Open Bracket: " & tok
					Dim fi%: fi = 1
					Dim ftok$, ftokType$
					ftok = GetToken(tok, fi, ftokType)
					While ftok <> ""
						Print ftok
						ftok = GetToken(tok, fi, ftokType)
					Wend
				Case "m"
					Print "mode"
			End Select
			tok = GetToken(sCell, si, tokType)
	Wend
End Function

Function GetToken(sCell$, ByRef si%, ByRef m$) as String
	Dim sonVars: sonVars = SondageReadSettings()
	Dim sonState: SondageStatement: sonState = new SondageStatement
	sCell = SondageExpandVariables(sCell, sonVars)
	Dim sCellLen: sCellLen = Len(sCell)
	Dim c$ 'current char
	Dim endIndex&
	Dim extract$
	Dim func$

	For si = si To sCellLen
		c = Mid(sCell, si, 1)
		If c = "(" Then
			extract = _ReadUntilCharacters(sCell, si + 1, Array(")"), endIndex)
			si = endIndex
			m = "("
			GetToken = extract
		ElseIf c = "@" Or c = "." Then
			m = c
			If si + 1 < sCellLen Then
				si = si + 1
				c = Mid(sCell, si, 1)
				If c = "{" Then
					extract = _ReadUntilCharacter(sCell,  si + 1, "}", endIndex)
				Else
					extract = _ReadUntilCharacters(sCell, si, Array(" ", "(", ""), endIndex)
				EndIf
				If ErrorLocal$ <> "" Or endIndex > sCellLen Then
					Print ErrorLocal$
					Exit Function
				End If
				If m = "@" Then 'Column mode
					Print "Column is '" & extract & "'"
				ElseIf m = "." Then
					Print "Style is '" & extract & "'"
				Else
					Print "Probably a function: " & extract
				End If
				si = endIndex
				GetToken = extract
				Exit Function
			End If
		Else
			m = ""
		End If
	Next 'si
End Function

Function SondageGetOpId(macroName$) as Integer
	Dim i%
	SondageGetOpId = -1
	For i = 0 To OperationTableLen
		If OperationTable(i).OpName = macroName Then
			SondageGetOpId = i
			Exit Function
		End If
	Next
End Function

Function SondageValidateDoc(oDoc as Object, docType$) as String
	Dim _err$ : _err = ""
	If Not oDoc.supportsService(docType) Then
		_err = oDoc.Title & " is not a valid Spreadsheet Document"
	ElseIf oDoc.CurrentController.ViewControllerName = "PrintPreview" Then
		_err = "Cannot run this macro in 'Print Preview', please close it and try again"
	End If
	SondageValidateDoc = _err
End Function

Sub SondageCall(opId%, oSheet, Ranges)
	Dim sonOp as SondageOperation: sonOp = OperationTable(opId)
	Dim script
	script=ThisComponent.scriptProvider.getScript("vnd.sun.star.script:" & sonOp.OpLocation & "."  & sonOp.OpName & "?language=Basic&location=document")
	script.invoke(Array(oSheet, Ranges), Array(), Array())
End Sub

Function SondageInferDocumentType(sonReports, aInputFiles as Variant) as SondageReport
	Dim sonReport as SondageReport
	Dim aMatch, used() as Boolean
	Dim iMatch%, iInputFile%, matched as Boolean, allMatched as Boolean

	For Each sonReport In sonReports
		Dim sMatch$: sMatch = SondageGetPropVal(sonReport.Settings, "Match")
		If sMatch <> "" Then
			aMatch = Split(sMatch, ";")
			If UBound(aMatch) = UBound(aInputFiles) Then
				ReDim used(UBound(aInputFiles))
				allMatched = True
				For iMatch = 0 To UBound(aMatch)
					matched = False
					For iInputFile = 0 To UBound(aInputFiles)
						If Not used(iInputFile) And Trim(aMatch(iMatch)) <> "" Then
							If InStr(LCase(aInputFiles(iInputFile)), LCase(Trim(aMatch(iMatch)))) > 0 Then
								used(iInputFile) = True
								matched = True
								Exit For
							End If
						End If
					Next iInputFile
					If Not matched Then
						allMatched = False
						Exit For
					End If
				Next iMatch
				If allMatched Then
					SondageInferDocumentType = sonReport
					Exit Function
				End If
			End If
		End If
	Next sonReport
End Function

Function SondageImportFiles(sondageReport as SondageReport, aInputFile as Variant, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean) as Variant
	Dim oDocs(0) as Variant
	Dim iInputFile%, sInputFile$
	ReDim oDocs(0 To UBound(aInputFile)) as Variant

	For iInputFile = 0 To UBound(aInputFile)
		sInputFile = aInputFile(iInputFile)
		oDocs(iInputFile) = SondageImportFile(sondageReport, sInputFile, sDocType, returnAlreadyOpenDoc, isHidden)
		If ErrorLocal$ <> "" Then Exit Function
	Next iInputFile
	SondageImportFiles = oDocs
End Function

Function SondageCSVHeader(sLine$) as Variant
	Dim fields() as String, value$, i&, n&, c$
	Dim quoted as Boolean
	ReDim fields(0)
	For i = 1 To Len(sLine)
		c = Mid(sLine, i, 1)
		If c = """" Then
			If quoted And Mid(sLine, i + 1, 1) = """" Then
				value = value & c
				i = i + 1
			Else
				quoted = Not quoted
			End If
		ElseIf c = "," And Not quoted Then
			fields(n) = value
			value = ""
			n = n + 1
			ReDim Preserve fields(n)
		Else
			value = value & c
		End If
	Next i
	fields(n) = value
	SondageCSVHeader = fields
End Function

Function SondageImportOptions(sondageReport as SondageReport, sInputFile$, Optional importAll as Boolean) as String
	Dim firstRow%, fileNum%, i%, j%, formatCode%
	Dim header$, headers, fieldName$, options$
	Dim reportField as SondageField
	Dim onlyConfigured as Boolean
	onlyConfigured = Not importAll And UCase(SondageGetPropVal(sondageReport.Settings, "ImportOnlyConfiguredFields")) <> "FALSE"
	firstRow = 1
	Select Case sondageReport.Title
	Case "INSPECTION", "TUBE", "CONSUMERS", "REFILL": firstRow = 4
	End Select
	Dim configuredRow$: configuredRow = SondageGetPropVal(sondageReport.Settings, "ImportStartRow")
	If configuredRow <> "" Then firstRow = CInt(configuredRow)
	If firstRow < 1 Then
		ErrorLocal$ = "ImportStartRow must be at least 1"
		Exit Function
	End If
	fileNum = FreeFile
	Open sInputFile For Input As #fileNum
	For i = 1 To firstRow
		Line Input #fileNum, header
	Next i
	Close #fileNum
	headers = SondageCSVHeader(header)
	options = "44,34,76," & firstRow & ","
	For i = LBound(headers) To UBound(headers)
		fieldName = UserFriendlyName(headers(i))
		formatCode = 1 ' Calc automatic selection when explicitly opted out
		If onlyConfigured Then formatCode = 9 ' Ignore unlisted CSV fields
		For j = LBound(sondageReport.Fields) To UBound(sondageReport.Fields)
			reportField = sondageReport.Fields(j)
			If reportField.Field = fieldName Then
				formatCode = 1 ' Listed field without a type: automatic selection
				If reportField.ImportFormat <> 0 Then formatCode = reportField.ImportFormat
				Exit For
			End If
		Next j
		If i > LBound(headers) Then options = options & "/"
		options = options & (i + 1) & "/" & formatCode
	Next i
	SondageImportOptions = options
End Function

Function SondageImportFile(sondageReport as SondageReport, sInputFile$, sDocType$, returnAlreadyOpenDoc as Boolean, Optional isHidden as Boolean, Optional importAll as Boolean) as Variant
	Dim oDoc
	Dim fileUrl
	Dim p(3) as new com.sun.star.beans.PropertyValue
	If IsMissing(isHidden) Then isHidden = True
	
	If returnAlreadyOpenDoc Then
		oDoc = ReturnComponentIfOpen(sInputFile)
		If Not IsNull(oDoc) Then
			If Not oDoc.isReadonly() Then
				SondageImportFile = oDoc
				Exit Function
			End If
		End If
	End If

	p(0).Name = "FilterName"
	p(0).Value = CSV_FILTER_NAME
	p(1).Name = "Hidden"
	p(1).Value = isHidden
	p(2).Name = "FilterOptions"
	' CSV sources may be open read-only; work in a writable, unnamed copy.
	p(3).Name = "AsTemplate"
	p(3).Value = True
	fileUrl = ConvertToUrl(sInputFile)
	If Not FileExists(fileUrl) Then
		ErrorLocal = "Cannot open file '" & fileUrl & "'"
		Exit Function
	End If
	p(2).Value = SondageImportOptions(sondageReport, sInputFile, importAll)
	oDoc = StarDesktop.loadComponentFromURL(fileUrl, "_blank", 0, p())
	' We may check if imported the correct file, by checking the number of columns
	'If oDoc.Sheets(0).Columns.Count = 2 Then
	'	MsgBox "Single column psv"
	'End If

	if IsEmpty(oDoc)Then
		ErrorLocal = "Failed to get Document for " & sInputFile
		Exit Function
	End If
	
	ErrorLocal = SondageValidateDoc(oDoc, sDocType)
	If ErrorLocal <> "" Then
		Exit Function
	End If
	SondageImportFile = oDoc
End Function

Sub SondageGenerateReport(sondageReport, oDoc)
	Print sondageReport.Title
End Sub

Function SondageReadSettings() as Variant
	Dim oDoc
	Dim oSheet
	Dim rangeAddress
	Dim oRange
	Dim iCell%, sKey$, sVal$
	Dim sonVars: sonVars = new Collection
	
	oSheet = ThisComponent.Sheets.getByName("Settings")
	If IsNull(oSheet) Then
		ErrorLocal$ = "Cannot find 'Settings' sheet"
		Exit Function
	End If
	oRange = UsedRangeCursor(oSheet)'.RangeAddress
	rangeAddress = oRange.RangeAddress
	
	For iCell = rangeAddress.StartRow To rangeAddress.EndRow
		sKey = oRange.getCellByPosition(0, iCell).String
		If sKey <> "" Then
			sVal = oRange.getCellByPosition(1, iCell).String
			sonVars.Add(item := sVal, key := sKey)
		End If
	Next 'iCell
	SondageReadSettings = sonVars
End Function

Sub SondageMain()
	Dim sonReports() as Variant
	Dim sonFields() as Variant
	Dim sonReport, sonField, sonStatement
	Dim iOpsLen%, iOp%, opId%
	Dim sInputFile$: sInputFile = "C:\Users\bhara\Desktop\GetPendingOrderConsumerDetailsDateRange(36).csv"
	Dim oDoc, oSheet, oUsedRange

	sonConf = SondageParseFieldConfiguration()
	If ErrorLocal$ <> "" Then
		MsgBox ErrorLocal$, 16
		Exit Sub
	End If
	
	sonReports = sonConf.Reports
	sonReport = SondageInferDocumentType(sonReports, sInputFile)
	oDoc = SondageImportFile(sonReport, sInputFile, True, False)
	
	' Copy the first, sheet if there is only one sheet in document
	If oDoc.Sheets.Count = 1 Then
			oDoc.Sheets.copyByName(oOrigSheet.Name, reportType & "WorkingCopy", 1)
	End If
	oSheet = oDoc.Sheets(1)
	'oSheet = oDoc.getSheets().getByIndex(0)
	oUsedRange = UsedRangeCursor(oSheet)
	If IsNull(oSheet) Then
		MsgBox "Input file is null", 16
		Exit Sub
	End If

	sonFields = sonReport.Fields
	Dim str$

	For Each sonField In sonFields
		'If Not IsEmpty(sonField) Then
		str = sonReport.Title & ": Field Variables: " & sonField.Field & ", with width: " &  sonField.Width & " with " & UBound(sonField.Statements) & " statements"
		For Each sonStatement In sonField.Statements
			iOpsLen = UBound(sonStatement.OpIds)
			str = str & " has condition " & sonStatement.Cond & " for " & sonStatement.Operand & "                  " & "Operations: " & "              " 
			Call SondageFilterColumn(oSheet, endColumn, endRow, "Area", orgCode & "_PortIn", sonStatement.Cond)
			For iOp = 0 To iOpsLen
				opId = sonStatement.OpIds(iOp)
				str = str & opId
				SondageCall(opId, oSheet, oRange)
			Next
			Print str
		Next
	Next
End Sub

Sub SondageFilterColumns(oSheet)
	Dim oFilterDesc
	Dim filterRange, oRange
	Dim oCursor, o, oColumnHeader, oDescriptor
	Dim newColumn : newColumn = endColumn + 1
	Dim oFields(0) as new com.sun.star.sheet.TableFilterField
	Dim filterCount as Long
	Dim filterColumnName as String
	Dim endRow&
	Dim filterContent as Variant, filterOperator as Variant

	If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL
	Print filterOperator

	On Error Goto ErrorHandler

	oRange = oSheet.getCellRangeByPosition(newColumn, 0, newColumn, endRow)
	oColumnHeader = oRange.getCellByPosition(0, 0)
	oColumnHeader.setString("0")	

	oDescriptor = oSheet.createReplaceDescriptor()

	filterRange = GetColumnRange(oSheet, endColumn, endRow, filterColumnName)
	oFilterDesc = filterRange.createFilterDescriptor(True)

	With oFields(0)
		.Field = filterRange.RangeAddress.StartColumn
		.IsNumeric = IsNumeric(filterContent)
		.Operator = filterOperator
		.StringValue = filterContent
		.NumericValue = filterContent
	End With

	oFilterDesc.setFilterFields(oFields())
	oFilterDesc.ContainsHeader = True
	oFilterDesc.UseRegularExpressions = False
	oSheet.filter(oFilterDesc)

	' TODO Check if there is a way to remove the 50,000 limit
	oRange.fillSeries(com.sun.star.sheet.FillDirection.TO_BOTTOM, com.sun.star.sheet.FillMode.SIMPLE, 0, 1, 50000)
	SortColumn(oSheet, 0, 1, newColumn, endRow, "0")

ErrorHandler:
	oSheet.filter(oSheet.createFilterDescriptor(True))
	oSheet.Columns.removeByIndex(newColumn, 1)
	Reset
End Sub

Function SondageExpandVariables(sCell$, sonVars as Variant, Optional varType$) as String
	Dim sCellLen: sCellLen = Len(sCell)
	Dim c$
	Dim si%, endIndex as Long
	Dim extract$, varState as Boolean
	
	If IsMissing(varType) Then varType = "$"

	For si = 1 To sCellLen
		c = Mid(sCell, si, 1)
		If c = varType Then
			varState = True
		ElseIf varState = True Then
			c = Mid(sCell, si, 1)
			If c = "{" Then
				extract = _ReadUntilCharacters(sCell,  si + 1, Array("}"), endIndex)
			Else
				extract = _ReadUntilEndOrCharacter(sCell, si, " ", endIndex)
			EndIf
			If ErrorLocal$ <> "" Or endIndex > sCellLen Then
				Print ErrorLocal$
				Exit Function
			End If
			SondageExpandVariables = SondageExpandVariables & sonVars.Item(extract)
			si = endIndex
			varState = False
		Else
			SondageExpandVariables = SondageExpandVariables & c
		End If
	Next 'si
End Function

Function SondageGetCondTypeFromString(opCond$) as Integer
		Dim condType%
		condType = com.sun.star.sheet.ConditionOperator.EQUAL
		SondageGetCondTypeFromString = condType

		If TypeName(opCond) <> "String" or Len(opCond) = 0Then
			condType = com.sun.star.sheet.ConditionOperator.NONE
			Exit Function
		End If

		Select Case opCond
			Case "<="
				condType = com.sun.star.sheet.ConditionOperator.LESS_EQUAL
			Case ">="
				condType = com.sun.star.sheet.ConditionOperator.GREATER_EQUAL
			Case "<>"
				condType = com.sun.star.sheet.ConditionOperator.NOT_EQUAL
			Case "><"
				condType = com.sun.star.sheet.ConditionOperator.BETWEEN
			Case "=="
				condType = com.sun.star.sheet.ConditionOperator.EQUAL
			Case Else
				' Check the first letter
				Select Case Left(opCond, 1)
					Case "<"
						condType = com.sun.star.sheet.ConditionOperator.LESS
					Case ">"
						condType = com.sun.star.sheet.ConditionOperator.GREATER
					Case "+"
						condType = com.sun.star.sheet.ConditionOperator.FORMULA
				End Select
		End Select
		 SondageGetCondTypeFromString = condType
End Function

Function _RemoveAllPrivateNamedRanges()
	Dim aNamedRanges, sNamedRange, i%
	aNamedRanges = ThisComponent.NamedRanges
	For i = 0 To aNamedRanges.getCount() - 1
		sNamedRange = aNamedRanges.getByIndex(i).Name
		If  InStr(1, sNamedRange, "Sondage_", 0) = 1 Then  ' sNamedRange starts with Sondage
			aNamedRanges.removeByName(sNamedRange)
		End If
	Next i
End Function

Function SondageParseFieldConfiguration() as SondageConfiguration
	Dim reportNames, aValues
	Dim oDoc, oSheet, oRange, oSearchRange
	Dim startRow&, endRow&, endColumn&, iRow&, iCol&
	Dim sCell, oCell
	
	' Used for ReDim Statements and Fields
	Dim sonConf as SondageConfiguration
	Dim sonReports() as SondageReport
	Dim sonStatements() as Variant
	Dim sonFields() as Variant
	Dim sonSettings() as Variant
	Dim opIds() as Integer

	' Remove OperationLimit later
	Dim stTokens(200) as String

	Dim sonReport as new SondageReport
	Dim sonField as new SondageField
	Dim sonStatement as new SondageStatement

	Dim iWidth
	Dim sStatements() as String, aHeaders() as String, sStatement$, sWidth$, opCond$
	Dim opTokens() as String

	SondageRegisterFunction("Standard.Sondage", "Select")
	' TODO Stub operation delete later
	' This is probably the modern verision of VLOOKUP that is based on column name
	' If something exists like this in Excel or Calc, just use its name
	SondageRegisterFunction("Standard.Sondage", "ColumnOperation")
	SondageRegisterFunction("Standard.Sondage", "ColorCell")
	SondageRegisterFunction("Standard.Sondage", "ColorRow")
	SondageRegisterFunction("Standard.Sondage", "Delete")

	oDoc = ThisComponent
	oSheet = oDoc.getSheets().getByName("FieldConfiguration")

	oRange = UsedRangeCursor(oSheet)
	startRow = 0
	endRow = oRange.RangeAddress.EndRow
	endColumn = oRange.RangeAddress.EndColumn

	ReDim Preserve aHeaders(endColumn) as String
   	For iCol = 0 To endColumn
   		aHeaders(iCol) = oSheet.getCellByPosition(iCol, iRow).getString()
   	Next iCol

	For iRow = startRow To endRow
		oCell = oSheet.getCellByPosition(0, iRow)
		sCell = oCell.getText().String
		If Left(sCell, 1) = "[" Then
			ReDim Preserve sonReports(UBound(sonReports) + 1) as SondageReport
			sonReport = sonReports(UBound(sonReports))
			sonReport.Fields = Array()
			sonReport.Settings = Array()
			' TODO Restrict the Title to certain values
			sonReport.Title = Mid(sCell, 2, Len(sCell) - 2)
			oCell.CellStyle = "Heading1"
			'Print sonReport.Title
		ElseIf Len(sonReport.Title) <> 0 Then
			If Left(sCell, 1) = "@" Then
				sonField = new SondageField
				Dim fieldSpec$, typePos&
				fieldSpec = Mid(sCell, 2)
				typePos = InStr(fieldSpec, ":")
				If typePos > 0 Then
					sonField.Field = Left(fieldSpec, typePos - 1)
					Select Case UCase(Mid(fieldSpec, typePos + 1))
					Case "TEXT": sonField.ImportFormat = 2
					Case "NUMBER", "AUTO": sonField.ImportFormat = 1
					Case "MM/DD/YY": sonField.ImportFormat = 3
					Case "DD/MM/YY": sonField.ImportFormat = 4
					Case "YY/MM/DD": sonField.ImportFormat = 5
					Case Else
						ErrorLocal$ = "Unknown import type in " & sCell
						Exit Function
					End Select
				Else
					sonField.Field = fieldSpec
				End If

				aValues = sonField.Values
				ReDim aValues(endColumn)
			   	For iCol = 0 To endColumn
			   		aValues(iCol) = oSheet.getCellByPosition(iCol, iRow).getString()
			   	Next iCol
			   	sonField.Values = aValues

				sonField.Statements = Array()
				sStatements = Split( _
					Trim(oSheet.getCellByPosition(1, iRow).getText().String), _
					CHR(13) _
				)
				sWidth = oSheet.getCellByPosition(2, iRow).getText().String
				If sWidth = "0" Then
					iWidth = 0
				ElseIf sWidth = "-1" or Len(sWidth) = 0 Then
					' Mark for deletion
					iWidth = -1
				Else
					iWidth = CLng(sWidth)
				End If
				sonField.Width = iWidth
				For Each sStatement In sStatements
						Dim ci: ci = 0
						Dim c$, pc$
						
						For ci = 1 To Len(sStatement)
							c = Mid(sStatement, ci, 1)
							If c = "$" Then
								' Read the rest of the word and store in a variable
								' This variable should be replaced with content from a collection above
								' Essentially implementing a variable like function
							End If
						Next
					stTokens = Split(sStatement, " then ")
					sonStatement = new SondageStatement

					Dim stToken
					Dim opToken$

					If UBound(stTokens) = 0 Then
						' Operand Only
						sonStatement.Operand = Trim(stTokens(0))
						'Print sonReport.Title & "Operand Only: " & stTokens(0)
						opTokens = Array()
					ElseIf UBound(stTokens) > 0 Then
						' Cond then Op
						opCond = Left(stTokens(0), 2)
	
						sonStatement.Cond = SondageGetCondTypeFromString(opCond)

						If sonStatement.Cond = com.sun.star.sheet.ConditionOperator.EQUAL Then
							sonStatement.Operand = Trim(stTokens(0))
						Else
							sonStatement.Operand = Trim(Right(stTokens(0),  Len(stTokens(0)) - 2) )
						End If
					End If 'UBound(stTokens)

					' After Reading the condition, save the operation after finding the Id
					If UBound(stTokens) > 0 Then
						opTokens = Split(stTokens(1), ",")
						For Each opToken In opTokens
							Dim opPureTokens() as String
							Dim opPureToken$
							Dim sonOpId%: sonOpId = -1
							opPureTokens = Split(Trim(opToken), "(")
							If UBound(opPureTokens) = -1 Then
								ErrorLocal$ = "FATAL: Error in row: " & iRow & ",  Operation is malformed"
								Exit Function
							End If
							opPureToken = Trim(opPureTokens(0))
							If Left(opPureToken, 1) = "@" Then
								Print "This is a @ column thing: " & opPureToken
								' TODO Construct optoken and id and push the instructions to list
								' FIXME This does not do much now
								sonOpId = SondageGetOpId("ColumnOperation")
							Else
								sonOpId = SondageGetOpId(opPureToken)
							End If
							If sonOpId = -1 Then
								ErrorLocal$ = "FATAL: Cannot retrieve the operation " & opPureToken & " in row " & iRow
								Exit Function
							End If
							opIds = sonStatement.OpIds
							ReDim Preserve opIds(UBound(sonStatement.OpIds) + 1) as Integer
							sonStatement.OpIds = opIds
							sonStatement.OpIds(UBound(sonStatement.OpIds)) = sonOpId
						Next 'opToken
					Else
						opTokens = Array(0)
					End If

					sonStatements = sonField.Statements
					ReDim Preserve sonStatements(UBound(sonField.Statements) + 1) as Variant
					sonField.Statements = sonStatements
					sonField.Statements(UBound(sonField.Statements)) = sonStatement
				Next	 'sOp

				sonFields = sonReport.Fields
				ReDim Preserve sonFields(UBound(sonFields) +  1) as Variant
				sonReport.Fields = sonFields
				sonReport.Fields(UBound(sonReport.Fields)) = sonField
			Else ' If != [ and != @
				sonSettings = sonReport.Settings
				ReDim Preserve sonSettings(UBound(sonSettings) + 1) as Variant
				sonSettings(UBound(sonSettings)) = CreateObject("com.sun.star.beans.PropertyValue")
				sonSettings(UBound(sonSettings)).Name = sCell
				sonSettings(UBound(sonSettings)).Value = oSheet.getCellByPosition(1, iRow).getText().String
				oCell.CellStyle = "Card"
				sonReport.Settings = sonSettings
			End If
		Else
			MsgBox "Syntax Error: should start with [HEADER] element", 16
			Exit Function
		End If
	Next 'iRow
	sonConf.Reports = sonReports
	sonConf.Headers = aHeaders
	SondageParseFieldConfiguration = sonConf
End Function