: 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 
823 
824 
825 
826 
827 
828 
829 
830 
831 
832 
833 
834 
835 
836 
837 
838 
839 
840 
841 
842 
843 
844 
845 
846 
847 
848 
849 
850 
851 
852 
853 
854 
855 
856 
857 
858 
859 
860 
861 
862 
863 
864 
865 
866 
867 
868 
869 
870 
871 
872 
873 
874 
875 
876 
877 
878 
879 
880 
881 
882 
883 
884 
885 
886 
887 
888 
889 
890 
891 
892 
893 
894 
895 
896 
897 
898 
899 
900 
901 
902 
903 
904 
905 
906 
907 
908 
909 
910 
911 
912 
913 
914 
915 
916 
917 
918 
919 
920 
921 
922 
923 
924 
925 
926 
927 
928 
929 
930 
931 
932 
933 
934 
935 
936 
937 
938 
939 
940 
941 
942 
943 
944 
945 
946 
947 
948 
949 
950 
951 
952 
953 
954 
955 
956 
957 
958 
959 
960 
961 
962 
963 
964 
965 
966 
967 
968 
969 
970 
971 
972 
973 
974 
975 
976 
977 
978 
979 
980 
981 
982 
983 
984 
985 
986 
987 
988 
989 
990 
991 
992 
993 
994 
995 
996 
997 
998 
999 
1000 
1001 
1002 
1003 
1004 
1005 
1006 
1007 
1008 
1009 
1010 
1011 
1012 
1013 
1014 
1015 
1016 
1017 
1018 
1019 
1020 
1021 
1022 
1023 
1024 
1025 
1026 
1027 
1028 
1029 
1030 
1031 
1032 
1033 
1034 
1035 
1036 
1037 
1038 
1039 
1040 
1041 
1042 
1043 
1044 
1045 
1046 
1047 
1048 
1049 
1050 
1051 
1052 
1053 
1054 
1055 
1056 
1057 
1058 
1059 
1060 
1061 
1062 
1063 
1064 
1065 
1066 
1067 
1068 
1069 
1070 
1071 
1072 
1073 
1074 
1075 
1076 
1077 
1078 
1079 
1080 
1081 
1082 
1083 
1084 
1085 
1086 
1087 
1088 
1089 
1090 
1091 
1092 
1093 
1094 
1095 
1096 
1097 
1098 
1099 
1100 
1101 
1102 
1103 
1104 
1105 
1106 
1107 
1108 
1109 
1110 
1111 
1112 
1113 
1114 
1115 
1116 
1117 
1118 
1119 
1120 
1121 
1122 
1123 
1124 
1125 
1126 
1127 
1128 
1129 
1130 
1131 
1132 
1133 
1134 
1135 
1136 
1137 
1138 
1139 
1140 
1141 
1142 
1143 
1144 
1145 
1146 
1147 
1148 
1149 
1150 
1151 
1152 
1153 
1154 
1155 
1156 
1157 
1158 
1159 
1160 
1161 
1162 
1163 
1164 
1165 
1166 
1167 
1168 
1169 
1170 
1171 
1172 
1173 
1174 
1175 
1176 
1177 
1178 
1179 
1180 
1181 
1182 
1183 
1184 
1185 
1186 
1187 
1188 
1189 
1190 
1191 
1192 
1193 
1194 
1195 
1196 
1197 
1198 
1199 
1200 
1201 
1202 
1203 
1204 
1205 
1206 
1207 
1208 
1209 
1210 
1211 
1212 
1213 
1214 
1215 
1216 
1217 
1218 
1219 
1220 
1221 
1222 
1223 
1224 
1225 
1226 
1227 
1228 
1229 
1230 
1231 
1232 
1233 
1234 
1235 
1236 
1237 
1238 
1239 
1240 
1241 
REM  *****  BASIC  *****
Option Explicit

Type SondageSettings
	oFieldAliasesRange as Variant
End Type

Type SondageContext
	oDoc as Variant
	oSheet as Variant
	oRange as Variant
	headerRow&
	startColumn&
	startRow&
	endColumn&
	endRow&
End Type

Private priceListPath as String

Public Function Env(Value As Variant) As String
    Env = Environ(Value)
End Function

Type Product
	Title as Variant ' com.sun.star.text.XText
	Price as Integer
	Description as String
End Type

'https://ask.libreoffice.org/t/how-to-know-if-the-file-is-open/77760/7
Function ReturnComponentIfOpen(Byval filePath As String) as Object
	Dim oComp
	filePath=ConvertToUrl(filePath)
	For Each oComp In StarDesktop.Components
		If HasUnoInterfaces(oComp, "com.sun.star.frame.XModel") Then  ' component which has URL
			If oComp.Url=filePath Then
				ReturnComponentIfOpen = oComp
				Exit Function
			End If
		End If
	Next oComp
End Function

Function CreateProperty(key as String, val as Variant) as com.sun.star.beans.PropertyValue
	Dim oProp As New com.sun.star.beans.PropertyValue
	oProp.Name = key
	oProp.Value = val
	CreateProperty = oProp
End Function

Function GetHomePath() as Object
	Dim oPathSub
	oPathSub = CreateUnoService("com.sun.star.util.PathSubstitution")
	GetHomePath = oPathSub.getSubstituteVariable("home") & "/"
End Function

Function ReadProductFromSheet(oSheet as Object, sProductName as String) as Product
	' TODO FIX: Return the correct Product details instead of first item
	Dim oProduct as Product
	Dim iPrice
	Dim oTitle
	Dim iChannel as Integer
	Dim oCalcDoc
	Dim oCursor, oCell
	Dim bProductFound: bProductFound = False
	Dim i, j, iRow, iColumn as Integer
	Dim sCalcFile: sCalcFile = ConvertToUrl(priceListPath)
	
	Dim oArgs(0) as new com.sun.star.beans.PropertyValue
	oArgs(0).Name = "Hidden"
	oArgs(0).Value = True

	oCursor = UsedRangeCursor(oSheet)
	iRow = oCursor.getRows().Count()
	iColumn = oCursor.getColumns().getCount()
	
	' TODO Use Column headers for retrieving data
	For i = 1 To iRow - 1
		oCell = oSheet.getCellByPosition(0, i)
		If oCell.String = sProductName Then
			bProductFound = True
			Goto CLOSE_SHEET_AND_REFLECT:
		End If
	Next i
	
CLOSE_SHEET_AND_REFLECT:
	If bProductFound Then
		oTitle = oSheet.getCellByPosition(1, i).getString()
		oProduct.Title = oCursor
		'############################
		oProduct.Price = oSheet.getCellByPosition(3, i).getValue()
	End If
	ReadProductFromSheet = oProduct
	oCalcDoc.close(True)
End Function

Function GetNumberFormatNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, formatStr as String) as Integer
	Dim formatNum as Long
	GetNumberFormatNumber = -1
	formatNum = oFormats.queryKey(formatStr, oLocale, False)
	' add formatStr if it doesn't exist
	If formatNum = -1 Then
		formatNum = oFormats.addNew(formatStr, oLocale)
	End If
	GetNumberFormatNumber = formatNum
End Function

Sub FormatRangeAsNumber(oLocale as com.sun.star.lang.Locale, ByRef oFormats, oRange, formatStr as String)
	' BASIC equivalent of 'Text to Columns'
	Dim formatNum as Long, i as Integer
	Dim oReplace
	oReplace = oRange.createReplaceDescriptor()
	
	If oRange.getCellByPosition(0,0).getValue() = 0 Then
		formatNum = GetNumberFormatNumber(oLocale, oFormats, formatStr)
		If formatNum = -1 Then
			ErrolLocal$ = "Cannot add " & formatStr & " as NumberFormat"
			Exit Sub
		End If
		' https://ask.libreoffice.org/t/macro-calc-convert-column-to-date-similar-text-to-columns/92168/20
		With oReplace
			.searchString = ".+"
			.replaceString = "&"
			.SearchRegularExpression = True
		End With

		oRange.NumberFormat = formatNum
		oRange.replaceAll(oReplace)
	End If
End Sub

Function GetColumnRange(ctx as SondageContext, columnName as String, Optional shouldIncludeHeader as Boolean) as Object
	Dim iHeaderPos
	If IsMissing(shouldIncludeHeader) Then shouldIncludeHeader = False
	iHeaderPos = GetHeaderPosition(ctx, columnName)
	If iHeaderPos = -1 Then
		GetColumnRange = ctx.oSheet.getCellRangeByPosition(0, 0, 0, 0)
		Exit Function
	End If
	GetColumnRange = ctx.oSheet.getCellRangeByPosition(iHeaderPos, IIf(shouldIncludeHeader, ctx.headerRow, ctx.startRow), iHeaderPos, ctx.endRow)
End Function

Function RemoveColumns(ctx as SondageContext, columnNames) as Long
	Dim columnName as String
	Dim iHeader as Integer
	RemoveColumns = ctx.endColumn
	For Each columnName in columnNames
		iHeader = GetHeaderPosition(ctx, columnName)
		If iHeader <> -1 Then
			ctx.oSheet.getColumns().removeByIndex(iHeader, 1)
			ctx.endColumn = ctx.endColumn - 1
		End If
	Next
	RemoveColumns = ctx.endColumn
End Function

Function RemoveColumnsExcept(ctx as SondageContext, columnNames as Variant) as Long
	Dim headerStr as String, columnName as String
	Dim i% : i = 0
	Dim rI% : rI = 0
	Dim columnsToRemove(ctx.endColumn) as String
	Dim headerRange, headerData
	Dim found as Boolean : found = False
	RemoveColumnsExcept = ctx.endColumn

	headerRange = ctx.oSheet.getCellRangeByPosition(0, 0, ctx.endColumn, 0)
	headerData = headerRange.getFormulaArray()

	' TODO Handle condition when columnNames does not have valid header
	' This causes an extra string element in the array
	For i = 0 To UBound(headerData(0))
		headerStr = headerData(0)(i)
		found = False
		For Each columnName in columnNames
			If headerStr = columnName Then
				found = True
				Exit For
			End If
		Next columnName
		If Not found Then
			columnsToRemove(rI) = headerStr
			rI = rI + 1
		End If
	Next i
	
	If i = 0 Then
		Exit Function
	End If

	If rI = 0 Then
		RemoveColumnsExcept = ctx.endColumn
		Exit Function
	End If
	ReDim Preserve columnsToRemove(rI - 1)
	
	RemoveColumnsExcept = RemoveColumns(ctx, columnsToRemove)
End Function

Sub ApplyTheme(ByRef oDoc, sFileName As String)
	Dim oFamilies
	Dim aOptions(0) as New com.sun.star.beans.PropertyValue
	Dim stylesDir()
	Dim StylePath as String
	GlobalScope.BasicLibraries.loadLibrary("Tools")
	oFamilies = oDoc.StyleFamilies
	StylesDir = GetOfficeSubPath("Template", "wizard/styles/")
	StylePath = StylesDir & sFileName
	aOptions(0).Name = "OverwriteStyles"
	aOptions(0).Value = true
	oFamilies.loadStylesFromURL(StylePath, aOptions())
End Sub

Function NaiveLastTable(ctx as SondageContext) as Long
	' Return the row position last table that is separated by an empty row
	Dim oRows
	Dim iRow as Long
	Dim usedRange
	NaiveLastTable = 0
	oRows = ctx.oRange.Rows

	For iRow = 0 To oRows.getCount() - 1
		If oRows.getByIndex(iRow).computeFunction(com.sun.star.sheet.GeneralFunction.COUNT) = 0 Then
			NaiveLastTable = iRow
		End If
	Next
End Function

Function IsValidFileName(fileName as String) as Boolean
    Dim invalidChars as String : invalidChars = "\/:*?""<>|"
    Dim c as String
    Dim i as Integer
    IsValidFileName = False
    For i = 1 To Len(fileName)	
   		c = Mid(fileName, i, 1)
    	If InStr(invalidChars, c) > 0 Then
    		Print "Invalid character '" & c & "' found in '" & fileName & "'"
    		Exit Function
    	End If
    Next
    IsValidFileName = True
End Function

Function ExportAs(oDoc, oSheet, exportPrefix$, exportDestDir$, exportExt$) as Boolean
	Dim cursor as Object
	Dim args(2) as New com.sun.star.beans.PropertyValue
	Dim fd(2) as New com.sun.star.beans.PropertyValue
	Dim fileName as String, fileUrl
	ExportAs = False
	On Error GoTo ErrorHandler
	
	If Not IsValidFileName(oSheet.Name) Then
		ErrorLocal$ = "Sheet has invalid characters for file export"
		Exit Function
	End If
	
	'If Right(exportPrefix, 1) = "/" Or Right(exportPrefix, 1) = "\" Then
	'	exportPrefix = Left(exportPrefix, Len(exportPrefix) - 1)

	fileUrl = ConvertToUrl(exportPrefix)
	If Not FileExists(fileUrl) Then
		ErrorLocal$ =  "FATAL: " & fileUrl & " does not exist"
		Exit Function
	End If

	fileUrl = ConvertToUrl(exportPrefix & GetPathSeparator() & exportDestDir)
	If Not FileExists(fileUrl) Then
			Mkdir fileUrl
	End If

	fileName = exportPrefix & GetPathSeparator() & exportDestDir & GetPathSeparator() & oSheet.Name & "." & exportExt
	fileUrl = ConvertToUrl(fileName)

	WIth fd(0) : .Name = "Selection" : .Value = UsedRangeCursor(oSheet) : End With
	' Disabled, because it conflicts with selection
	With fd(1) : .Name = "SinglePageSheets" : .Value = False : End With
	With fd(2) : .Name = "IsSkipEmptyPages" : .Value = True : End With

	If exportExt = "pdf" Then
		With args(0) : .Name = "FilterName" : .Value = "calc_pdf_Export" : End With
	ElseIf exportExt = "ods" Then
		With args(0) : .Name = "FilterName" : .Value = "calc8" : End With
	Else
		ErrorLocal$ = "FATAL: Export type '" & exportExt  & "' not handled"
	End If
	
	With args(1) : .Name = "FilterData" : .Value = fd : End With
	With args(2) : .Name = "Overwrite" : .Value = True : End With

	oDoc.storeToURL(fileUrl,  args)
	ExportAs = True
	Exit Function
ErrorHandler:
	ErrorLocal$ = "FATAL: ExportPDF: Unknown error"
End Function

Sub ListOfActiveCustomers()
	Dim oSheet, destSheet, cursor, oRange
	Dim startRow as Long
	Dim endRow as Long
	Dim startColumn as Long
	Dim endColumn as Long
	Dim requiredFields()
	Dim requiredFieldIndices() as Integer
	Dim iColumn as Integer, iRequiredField as Integer
	Dim headerCellStr as String

	oSheet = ThisComponent.Sheets(0)
	cursor = UsedRangeCursor(oSheet)

	' Skip Header
	startRow =  NaiveLastTable(cursor)
	endRow = cursor.RangeAddress.EndRow
	endColumn = cursor.RangeAddress.EndColumn
	' TODO Use data from PhoneNumber if some MobileNumber is missing
	requiredFields = Array("ConsumerNumber", "ConsumerName", "MobileNumber", "AreaCodeDesc", "LastDelivDate")
	'oSheet.Rows.removeByIndex(0, 3)

	For iColumn = startColumn To endColumn
		headerCellStr = oSheet.getCellByPosition(iColumn, startRow, iColumn, startRow).getString()
		For iRequiredField = 0 To UBound(requiredFields)
			If headerCellStr = requiredFields(iRequiredField) Then
				' TODO Allocate memory before hand and use a tracker index?
				ReDim Preserve requiredFieldIndices(UBound(requiredFieldIndices) + 1)
				requiredFieldIndices(UBound(requiredFieldIndices)) = iColumn
			End If
		Next iRequiredField
	Next iColumn
	destSheet = NewSheet(oDoc, "SBC Connection")
	
	Print Join(requiredFieldIndices)
	
	' TODO Ignore the Header Table if it exists
	' i.e. If two tables exists, assume the first one to be header table
	' and ignore it while copying to new sheet
	
	' Copy the cells in 'requiredFieldIndices' to 'destSheet'
End Sub

Sub CombineFiles(sFolder as String, fileRegex as String)
	Dim sFile
	Dim sFiles as Variant
	Dim i as Integer: i = 0
	Dim oDoc as Variant
	Dim dstSheet
	Dim oDstCursor
	Dim oSrcCursor
	Dim rangeAddress
	Dim oSheet
	If Not FileExists(sFolder) Then
		ErrorLocal$ = "sFolder path: '" & sFolder & "' does not exist"
		Exit Sub
	End If
	
	sFile = Dir( sFolder & "\" & fileRegex, 0)
	
	If  IsEmpty(oDoc) Then
		oDoc = ImportReportFile(sFolder & "\" & sFile, False)
		if IsEmpty(oDoc) Then
			ErrorLocal$ = "Failed to get Document for " & sInputFile
			Exit Sub
		End If
		If Not oDoc.supportsService( "com.sun.star.sheet.SpreadsheetDocument")  Then
			Print "The imported document is not a sheet document"
		End If
		dstSheet = oDoc.getSheets().getByIndex(0)
	End If
		
	sFile = Dir()
	Do While(sFile <> "")
		oDstCursor = UsedRangeCursor(dstSheet)
		i = i + 1

		oDoc.getSheets().insertNewByName(CStr(i), i)
		oSheet = oDoc.getSheets().getByIndex(i)
		If IsEmpty(oSheet) Then
			ErrorLocal$ = "Cannot create new sheet"
			Exit Sub
		End If
		
		oSheet.link(ConvertToUrl(sFolder & "\" & sFile), CStr(i),  CSV_FILTER_NAME,  PENDING_CSV_FILTER_OPTIONS, com.sun.star.sheet.SheetLinkMode.NORMAL)
		
		oSrcCursor = UsedRangeCursor(oSheet, 1)
		
		dstSheet.copyRange(dstSheet.getCellByPosition(0, oDstCursor.RangeAddress.EndRow + 1).getCellAddress(), oSrcCursor.RangeAddress)
		sFile = Dir()
	Loop
End Sub

Function UsedRangeCursor(oSheet as Variant, Optional rowsToSkip as Integer) as Variant
	Dim oCursor
	Dim i as Integer
	oCursor = oSheet.createCursor()
	oCursor.gotoStartOfUsedArea(False)
	If Not IsMissing(rowsToSkip) Then oCursor.gotoOffset(0, rowsToSkip, False)
	oCursor.gotoEndOfUsedArea(True)
	UsedRangeCursor = oCursor
End Function

Function GetProductNames() as Variant
	GetProductNames = Array( _
		5300, "14.2", _
		5350, "14.2s", _
	)
	' TODO finish deploying the extension and push extension to git
End Function

Function ProductDescrption(productCode as Integer) as String
	Dim i as Long
	Dim productNames: productNames = GetProductNames()
	ProductDescription = ""
	For i = 0 To UBound(productNames) Step 2
		If productNames(i) = productCode Then
			ProductDescription = productNames(i + 1)
		End If
	Next i
End Function

Function GetValueForKey(oRange as Variant, key as String, Optional valueOffset%) as Object
	' Returns a ScCellObj
	Dim oSearchRange
	Dim oSearchDescriptor
	Dim oCell

	If oRange.Columns.Count < 2 Then
		MsgBox "GetValueForKeyCannot have columns less than 2", 16
		GetValueForKey = oCell
		Exit Function
	End If
	
	oSearchRange = oRange.getCellRangeByPosition(0, 0, 0,  oRange.Rows.Count - 1)
	oSearchDescriptor = oSearchRange.createSearchDescriptor()
	With oSearchDescriptor
		.SearchString = key
		.SearchWords = True
		.SearchCaseSensitive = True
	End With
	oCell = oSearchRange.findFirst(oSearchDescriptor)

	If Not IsNull(oCell) Then
		If IsMissing(valueOffset) Then
			valueOffset = oCell.RangeAddress.StartColumn + 1
		End If
		oCell = oRange.getCellByPosition( valueOffset, _
			oCell.RangeAddress.StartRow _
		)
	End If
	GetValueForKey = oCell
End Function

Function UserFriendlyName(str as String) as String
	' Checks headerName and headerNameMatches for the string 'str',
	' If it's not available there, a naïve implementation adds spacing to 'str'
	Dim l as Long
	Dim c as String
	Dim i as Long
	Dim prevChar$
	Dim oValCell

	str = Trim(str)
	oValCell =  GetValueForKey(GlobalSondageSettings.oFieldAliasesRange, str)
	If Not IsNull(oValCell) Then
		UserFriendlyName = oValCell.String
		Exit Function
	End If
	
	l = Len(str)
	' Check with header "database"
	For i = 0 To l
		c = Mid(str, i + 1, 1)
		If i > 1 And (c > "A" And c < "Z") Then
				' Only prepend space if 'c' is not the first character...
				' or previous char doesn't have space
				UserFriendlyName = UserFriendlyName &  IIf(prevChar = " ", "", " ")  & c
		Else
			UserFriendlyName = UserFriendlyName & c
		End If
		prevChar = c
	Next
End Function

Sub SortColumn(ctx as SondageContext, columnName1 as String, Optional columnName2 as String)
	Dim iHeaderPos as Long
	Dim oSortFields(1) as new com.sun.star.util.SortField
	Dim oSortDesc(1) as new com.sun.star.beans.PropertyValue

	iHeaderPos = GetHeaderPosition(ctx, columnName1)
	If iHeaderPos = -1 Then
		Exit Sub
	End If


	' Area
	oSortFields(0).Field = iHeaderPos
	oSortFields(0).SortAscending = True

	' FIXME This should be handled from the sheet settings
	If Not IsMissing(columnName2) Then
		iHeaderPos = GetHeaderPosition(ctx, columnName2)
		If iHeaderPos = -1 Then
			Exit Sub
		End If
		oSortFields(1).Field = iHeaderPos
		oSortFields(1).SortAscending = True
	End If

	oSortDesc(0).Name = "SortFields"
    oSortDesc(0).Value = oSortFields
	oSortDesc(1).Name = "ContainsHeader"
	oSortDesc(1).Value = True
	
	ctx.oRange.Sort(oSortDesc)
End Sub

Function NewSheet(oDoc, sheetName as String) as Object
			Dim sheets as Object
			sheets = oDoc.Sheets()
			If Not sheets.hasByName(sheetName) Then
				sheets.insertNewByName(sheetName, sheets.getCount())
			End If
			NewSheet = sheets.getByName(sheetName)
End Function

Sub CleanColumnHeaders(ctx as SondageContext)
	Dim cell as Object
	Dim neatName as String
	Dim i as Integer
	For i = ctx.startColumn To ctx.endColumn
		cell = ctx.oSheet.getCellByPosition(i, ctx.headerRow)
		neatName = cell.getString()
		neatName = UserFriendlyName(neatName)
		cell.setString(neatName)
	Next
End Sub

Sub RemoveExtraMergeCells(oDoc as Object, oSheet as Object, oRangeAddress as Variant)
	Dim oRange as Object
	Dim oSortFields(0) as new com.sun.star.util.SortField
	Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue
	Dim endRow as Long
	
	endRow = oRangeAddress.EndRow
	lastColumn = oRangeAddress.EndColumn
		
	rem set the range on which to sort'

	'oRange = oSheet.getCellRangeByName("A2:F20")
	oRange = oSheet.getCellRangeByPosition(0, 0, lastColumn, 0)
	oDoc.getCurrentController().select(oRange)
	initialColumnCount = oRange.Columns.getCount() - 1
	deletedColumns = 0
	For j = 0 To (initialColumnCount - deletedColumns)
		oCell = oRange.getCellByPosition(j, 0)
		con = oCell.String
		If con = "" Then
			oRange.Columns.removeByIndex(j, 1)
			deletedColumns = deletedColumns - 1
		Else
			Print con
		End If
	Next
End Sub

Sub UnFreezeSelection(oDoc as Object)
	Dim dispatcher as Object
	dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
	dispatcher.executeDispatch(oDoc.getCurrentController().getFrame(), ".uno:FreezePanes", "", 0, Array())
End Sub

Function GetHeaderPosition(ctx as SondageContext, searchString$, Optional isRoughHeaderMatch as Boolean) as Integer
	Dim iColumn as Integer
	Dim oCell as Object
	Dim cellString as String
	GetHeaderPosition = -1
	If IsMissing(isRoughHeaderMatch) Then isRoughHeaderMatch = False
	If searchString = "" Then
		Exit Function
	End If

	For iColumn = ctx.startColumn To ctx.endColumn
        oCell = ctx.oSheet.getCellByPosition(iColumn, ctx.headerRow)
        cellString = oCell.String
        If cellString = "" Then
        	'ErrorLocal$ = "BAD ARGUMENT: Cannot have empty columns within UsedRange, endColumn is " & CStr(endColumn)
        	Exit Function
        End If

		' TODO Implement regex matching
		If isRoughHeaderMatch = True Then
			If InStr(cellString, searchString) Then
				GetHeaderPosition = iColumn
				Exit Function
			End If
        ElseIf  cellString = searchString Then
            GetHeaderPosition = iColumn
            Exit Function
        End If
    Next iColumn
End Function

Function HighlightRowWithColumn(ctx as SondageContext, _
		highlightColumnName, highlightValue, Optional highlightColor as Long) as Long
	Dim currentStr as String
	Dim oCell as Object
	Dim oCellRange as Object
	Dim str as String
	Dim iSearchColumn as Long
	Dim i as Integer
	Dim highlightCount as Long
	
	If IsMissing(highlightColor) Then
		highlightColor = RGB(255, 255, 0)
	End If

	' Search for column position that has highlightBasedOn
	iSearchColumn = GetHeaderPosition(ctx, highlightColumnName)
	If iSearchColumn = -1 Then Exit Function
	For i = ctx.startRow To  ctx.endRow
		oCell = ctx.oSheet.getCellByPosition(iSearchColumn, i)
		If oCell.getString() = highlightValue Then
			oCellRange = ctx.oSheet.getCellRangeByPosition(0, i, ctx.endColumn, i)
			oCellRange.CellBackColor = highlightColor
			highlightCount = highlightCount + 1
		End If
	Next i
	HighlightRowWithColumn = highlightCount
End Function

Function ComputeOnRange(ctx as SondageContext, columnName as String, computeFunc%) as Long
	Dim headerPos
	Dim column
	Dim val
	headerPos = GetHeaderPosition(ctx, columnName)
	If headerPos = -1 Then
		ErrorLocal$ =  "Cannot find a column header that starts with '" & columnName & "'"
		Exit Function
	End If
	' TODO Check if the column we are searching, actually has date values.
	column = ctx.oSheet.getCellRangeByPosition(headerPos, 1, headerPos, ctx.endRow)
	ComputeOnRange =  column.computeFunction(computeFunc)
End Function

Sub ColumnJoin(joinChar$, idColumnName, dstCtx as SondageContext, dstColumnName$, srcCtx as SondageContext, srcColumnName$)
	Dim i&, j&
	Dim dstEndRow&, dstEndColumn%, srcEndRow&, srcEndColumn%
	Dim dstColumnIdx%, srcColumnIdx%
	Dim dstStr$, dstCell
	Dim dstRange, srcRange, srcRangeAddress, dstRangeAddress
	Dim oTextCursor, oService, statusBar
	statusBar = ThisComponent.CurrentController.StatusIndicator
	oService = CreateUNOService("com.sun.star.sheet.FunctionAccess")
	
	dstRange = UsedRangeCursor(dstCtx.oSheet)
	dstRangeAddress = dstRange.RangeAddress
	srcRange = UsedRangeCursor(srcCtx.oSheet)
	srcRangeAddress = srcRange.RangeAddress

	dstEndRow = dstRangeAddress.EndRow
	srcEndRow = srcRangeAddress.EndRow
	
	dstColumnIdx = GetHeaderPosition(dstCtx, dstColumnName)
	srcColumnIdx = GetHeaderPosition(srcCtx, srcColumnName)


	Dim srcColumnIdIdx: srcColumnIdIdx = GetHeaderPosition(srcCtx, idColumnName)
	Dim newSrcRange
	newSrcRange = srcSheet.getCellRangeByPosition(srcColumnIdIdx, srcCtx.startRow, srcCtx.endColumn, srcCtx.endRow)
	
	Dim dstColumnIdIdx: dstColumnIdIdx = GetHeaderPosition(dstCtx, idColumnName)

	statusBar.start("Merging Columns", 100)
	For i = dstStartRow To dstEndRow
		Dim srcCell
		Dim srcStr$
		Dim what$

		statusBar.setText("Merging " & CStr(i) & "/" & dstEndRow)
		statusBar.setValue((i / dstEndRow) * 100)

		dstCell = dstRange.getCellByPosition(dstColumnIdx, i)
		dstStr = dstCell.getText().String
		what = dstRange.getCellByPosition(dstColumnIdIdx, i).getText().String
		
		srcStr = oService.callFunction("VLOOKUP", Array(what, newSrcRange, srcColumnIdx, True))


		dstCell.getText().setString(dstStr & joinChar & srcStr)

		oTextCursor = dstCell.getText().createTextCursor()
	    oTextCursor.gotoStart(False)
	    oTextCursor.goRight(Len(dstStr), True)
	    'oTextCursor.CharWeight = com.sun.star.awt.FontWeight.BOLD
	    oTextCursor.goRight(1, False)
	    oTextCursor.gotoEnd(True)
	    oTextCursor.CharHeight = 7
	    srcStr = ""
	    what = ""
	Next
	statusBar.end()
End Sub

' TODO Use a general function that takes arrays
' and instead of the function ShortenDirections, use
' ReplaceArrays to make it more usable across other projects.
Sub ShortenDirections(ctx as SondageContext, columnIdx as Integer)
	'Shorten East as E. etc
	Dim toReplace() as String
	Dim toReplaceWith() as String
	Dim i as Long
	Dim oDescriptor
	Dim oColumn
	Dim columnToReplace
	oColumn = ctx.oSheet.getColumns().getByIndex(columnIdx)
	' TODO arrange it with convention
	toReplace() = Array("East", "West", "South", "North")
	toReplaceWith() = Array("E.", "W.", "S.", "N.")
	oDescriptor = oColumn.createReplaceDescriptor()
	For i = LBound(toReplace) To UBound(toReplace)
		With oDescriptor
			.SearchString = toReplace(i)
			.ReplaceString = toReplaceWIth(i)
		End With
		oColumn.replaceAll(oDescriptor)
	Next i
End Sub

Sub FilterColumn(ctx as SondageContext, filterColumnName as String, filterContent as Variant, Optional filterOperator as Variant, Optional filterUseRegex as Boolean)
	Dim oFilterDesc
	Dim filterRange, oRange
	Dim oCursor, o, oDescriptor
	'Dim oColumnHeader
	Dim newColumn : newColumn = ctx.endColumn + 1
	Dim oFields(0) as new com.sun.star.sheet.TableFilterField
	Dim filterCount as Long

	If IsMissing(filterOperator) Then filterOperator = com.sun.star.sheet.FilterOperator.EQUAL
	If IsMissing(filterUseRegex) Then filterUseRegex = False
	
	'On Error Goto ErrorHandler
	
	oRange = ctx.oSheet.getCellRangeByPosition(newColumn, 0, newColumn, ctx.endRow)
	'oColumnHeader = oRange.getCellByPosition(0, 0)
	'oColumnHeader.setString("0")	

	oDescriptor = ctx.oSheet.createReplaceDescriptor()

	filterRange = GetColumnRange(ctx, 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 = filterUseRegex
	ctx.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(ctx.oSheet, 0, 1, newColumn, endRow, "0")

	'filterCount = oRange.computeFunction(com.sun.star.sheet.GeneralFunction.COUNT)	
	'ctx.oSheet.Rows.removeByIndex(filterCount, (ctx.endRow - filterCount) + 1)

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

Sub  SetHeader(ByRef oPageStyle, Optional sLeftHeader$, Optional sCenterHeader$, Optional sRightHeader)
	Dim oHeader
	Dim oText
	Dim oTextCursor

	oHeader = oPageStyle.RightPageHeaderContent
	
	If Not IsMissing(sLeftHeader) Then
		oText = oHeader.LeftText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sLeftHeader, true)
	End If
	
	If Not IsMissing(sCenterHeader) Then
		oText = oHeader.CenterText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sCenterHeader, true)
	End If
	
	If Not IsMissing(sRightHeader) Then
		oText = oHeader.RightText
		oTextCursor = oText.createTextCursor()
		oText.insertString(oTextCursor, sRightHeader, true)
	End If
	
	oPageStyle.RightPageHeaderContent = oHeader
End Sub
				
Sub SondageRestructureColumns(ctx as SondageContext, aColumnWidth as Variant)
	' columnWidthArray has values like Array(Array("Area", 0), Array("ID", 2000))
	' 0 means autofill
	Dim columnWidth, iField%
	Dim sField$, iWidth as Variant
	Dim oColumn
	Dim iHeaderColumn

	For iField = LBound(aColumnWidth) To UBound(aColumnWidth)
		sField = aColumnWidth(iField, 0)
		iWidth = aColumnWidth(iField, 1)

		If Not IsEmpty(iWidth) Then
			iHeaderColumn = GetHeaderPosition(ctx, sField)
			If iHeaderColumn = -1 Then
				If iWidth = -1 Then
					' No-Op as the field already does not exist
				ElseIf iWidth >= 0 Then
					SondageAppendColumn(ctx, sField)
				    iHeaderColumn = GetHeaderPosition(ctx, sField)
				Else
					ErrorLocal$ = "Cannot find: " & sField & " in headers": Exit Sub
				End If
			End If
	
			If iHeaderColumn <> -1 Then
				oColumn = ctx.oSheet.getColumns().getByIndex(iHeaderColumn)
				If iWidth = -1 Then
					'ctx.oSheet.getColumns().removeByIndex(iHeaderColumn, 1)
					oColumn.IsVisible = False
					'ctx.endColumn = ctx.endColumn - 1
				Else
					If iWidth = 0 Then
						oColumn.OptimalWidth = True
					Else
						oColumn.Width = iWidth
					End If
			End if
		End If
		End If
	Next iField
	ErrorLocal$ = ""
End Sub

Sub ReArrangeResultToHeader(ctx as SondageContext, Optional headerStyle$)
	' Assumptions kept local to this transform:
	' - row 1 is the first data/subtotal row; row 0 is left alone
	' - column A contains LibreOffice subtotal Result markers and group labels
	' - generated headers are written from column B through the last used column
	' - cells with style "Result" are subtotal rows
	' - the last Result row is the grand total, mirrored to the top and removed below
	' - one extra top row is for grand total, one is for the first subtotal header
	Dim startRow&, nRow&, nCol&, insertRow&, topRow&, totalRow&, removeRow&
	Dim oDoc, oRange, oUsedRangeAddress
	Dim resultRanges
	Dim oAddrs()
	Dim oAddr
	Dim oFound, oCells
	Dim insertRowCell
	Dim oSearchDesc

	If IsMissing(headerStyle) Then headerStyle =  "Accent 1"
	startRow = 1

	oUsedRangeAddress = UsedRangeCursor(ctx.oSheet).RangeAddress
	oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0, oUsedRangeAddress.EndRow)

	oSearchDesc = oRange.createSearchDescriptor()
	oSearchDesc.SearchStyles = True
	oSearchDesc.SearchString = "Result"

	Dim sResult, sGroupBy
	Dim oRows, oCols, emptyValue as Object
	oRows = ctx.oSheet.getRows()
	oCols = ctx.oSheet.getColumns()
	Dim colRange

	' Construct first row and column to be same as others
	topRow = startRow
	totalRow = -1
	removeRow = -1
	oRows.insertByIndex(startRow, 2)
	oUsedRangeAddress.EndRow = oUsedRangeAddress.EndRow + 2
	insertRowCell = ctx.oSheet.getCellByPosition(0, startRow + 1)
	insertRowCell.CellStyle = "Result"
	startRow = startRow + 1

	oFound = ctx.oSheet.findFirst(oSearchDesc)
	Do While Not IsNull (oFound)
		'Print  "Name is: " & oFound.getText().getString()
		insertRow = startRow
		insertRowCell = ctx.oSheet.getCellByPosition(1, insertRow)
		startRow = oFound.RangeAddress.StartRow
		If startRow > oUsedRangeAddress.EndRow Then
			oFound = emptyValue
		Else
			sResult = ctx.oSheet.getCellByPosition(0, startRow).getText().String
			If sResult <> "" Then
				sGroupBy = ctx.oSheet.getCellByPosition(0, startRow - 1).getText().String
				colRange = ctx.oSheet.getCellRangeByPosition(1, insertRow, oUsedRangeAddress.EndColumn, insertRow)
				colRange.merge(True)
				colRange.CellStyle = headerStyle
				insertRowCell.getText().setString(sGroupBy & "   (" & sResult & ")")

				' Last Result row is the grand total; mirror it at the top and remove the bottom copy later.
				insertRowCell = ctx.oSheet.getCellByPosition(1, topRow)
				insertRowCell.getText().setString(sGroupBy & "   (" & sResult & ")")
				colRange = ctx.oSheet.getCellRangeByPosition(1, topRow, oUsedRangeAddress.EndColumn, topRow)
				colRange.merge(True)
				colRange.CellStyle = headerStyle
				totalRow = startRow
				removeRow = insertRow
			End If

			oRange = ctx.oSheet.getCellRangeByPosition(0, startRow, 0,  oUsedRangeAddress.EndRow)
			oFound = ctx.oSheet.findNext(oRange, oSearchDesc)
		End If
	Loop

	' Delete bottom-up so the first delete cannot shift the second row number.
	If totalRow > removeRow Then
		If totalRow <> -1 Then oRows.removeByIndex(totalRow, 1)
		If removeRow <> -1 Then oRows.removeByIndex(removeRow, 1)
	Else
		If removeRow <> -1 Then oRows.removeByIndex(removeRow, 1)
		If totalRow <> -1 Then oRows.removeByIndex(totalRow, 1)
	End If
	oCols.removeByIndex(0, 1)
End Sub














sub FiltersToCalc
	Dim oFF ' FilterFactory service
	Dim oFilterNames ' Array of filter names.
	Dim oDoc ' Document created to hold the filter names.
	Dim oSheet ' Sheet that will hold the filter information.
	Dim oCell ' Cell to update
	
	 Dim i% ' Index Variable.
	Dim fProps() ' Properties for each filter.
	Dim fp% ' Filter property index
	Dim fpCol% ' Column for the specified filter data.
	Dim s$ ' Work string that holds some property values.
	Dim iUserData% ' For enumerating array property values.
	Dim oProp ' A single property.
	Dim oArrayData ' Array of user properties.
	Dim sPropNames(7) As String
	Dim flags As Long
	sPropNames(0) = "Name"
	sPropNames(1) = "Import"
	sPropNames(2) = "Export"
	sPropNames(3) = "Options"
	sPropNames(4) = "Visible"
	sPropNames(5) = "Flags"
	sPropNames(6) = "DocumentService"
	sPropNames(7) = "UIName"
	oFF = createUnoService( "com.sun.star.document.FilterFactory" )
	oFilterNames = oFF.getElementNames()
	' Create a Calc doc and save the filter names to it.
	oDoc = StarDesktop.loadComponentFromURL( "private:factory/scalc", "_blank", 0, Array() )
	oSheet = oDoc.getSheets().getByIndex(0)
	' Print the filter names into a document.
	For i = LBound( oFilterNames ) To UBound( oFilterNames )
	fProps() = oFF.getByName(oFilterNames(i))
	For fp = LBound(fProps) To UBound(fProps)
	oCell = oSheet.getCellByPosition(fp, i+1)
	oProp = fProps(fp)
	fpCol = FindInArrayAdd(oProp.Name, sPropNames)
	If fpCol > UBound(sPropNames) Then
	ReDim Preserve sPropNames(fpCol) As String
	sPropNames(fpCol) = oProp.Name
	End If
	oCell = oSheet.getCellByPosition(fpCol, i+1)
	If Not IsArray(oProp.Value) Then
	oCell.setString(oProp.Value)
	If oProp.Name = "Flags" Then
	flags = oProp.Value
	oCell.setString(CStr(flags) & " = " & flags_int2str(flags))
	If flags and 1 Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Import", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If flags and 2 Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Export", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If flags and 128 Then
	 oCell = oSheet.getCellByPosition(FindInArrayAdd("Options", sPropNames), i+1)
	oCell.setString("X")
	Endif
	If ((flags and 4096) or (flags and 8192)) Then
	oCell = oSheet.getCellByPosition(FindInArrayAdd("Visible", sPropNames), i+1)
	oCell.setString("X")
	Endif
	End If
	ElseIf LBound(oProp.Value) <= UBound(oProp.Value) Then
	s = ""
	oArrayData = oProp.Value
	For iUserData = LBound(oArrayData) To UBound(oArrayData)
	If VarType(oArrayData(iUserData)) = 8 Then
	s = s & "(String:" & oArrayData(iUserData) & ")"
	Else
	s = s & "(" & oArrayData(iUserData).Name & ":" & oArrayData(iUserData).Value & ")"
	End If
	Next
	oCell.setString(s)
	End If
	Next
	Next
	For fp = LBound(sPropNames) To Ubound(sPropNames)
	oCell = oSheet.getCellByPosition(fp, 0)
	oCell.setString(sPropnames(fp))
	Next
	FinalFormat(oDoc)
End Sub
function flags_int2str(flags as long) as string
Dim cflags as long
Dim strval as string
Dim curFlag As Long
cflags = flags
strval = ""
if cflags and &H00000001 then
strval = strval + " Import"
cflags = cflags-1
endif
if cflags and &H00000002 then
strval = strval + " Export"
cflags = cflags-2
endif
if cflags and &H00000004 then
strval = strval + " Template"
cflags = cflags-4
endif
if cflags and &H00000008 then
strval = strval + " Internal"
cflags = cflags-8
endif

 if cflags and &H00000010 then
strval = strval + " TemplatePath"
cflags = cflags-16
endif
if cflags and &H00000020 then
strval = strval + " Own"
cflags = cflags-32
endif
if cflags and &H00000040 then
strval = strval + " Alien"
cflags = cflags-64
endif
if cflags and &H00000080 then
strval = strval + " UseOptions"
cflags = cflags-128
endif
if cflags and &H00000100 then
strval = strval + " Default"
cflags = cflags-256
endif
if cflags and &H00000200 then
strval = strval + " Executable"
cflags = cflags-512
endif
if cflags and &H00000400 then
strval = strval + " SupportSelection"
cflags = cflags-1024
endif
if cflags and &H00000800 then
strval = strval + " MapToAppPlug"
cflags = cflags-2048
endif
if cflags and &H00001000 then
strval = strval + " NotInFileDialog"
cflags = cflags-4096
endif
if cflags and &H00002000 then
strval = strval + " NotInChooser"
cflags = cflags-8192
endif
if cflags and &H00004000 then
strval = strval + " Acynchronas"
cflags = cflags-16384
endif
if cflags and &H00008000 then
strval = strval + " Creator"
cflags = cflags-32768
endif
if cflags and &H00010000 then
strval = strval + " Readonly"
cflags = cflags-65536
endif
if cflags and &H00020000 then

 strval = strval + " NotInstalled"
cflags = cflags-131072
endif
if cflags and &H00040000 then
strval = strval + " ConsultService"
cflags = cflags-262144
endif
if cflags and &H00080000 then
strval = strval + " 3rdPartyFilter"
cflags = cflags-524288
endif
if cflags and &H00100000 then
strval = strval + " Packed"
cflags = cflags-1048576
endif
if cflags and &H00200000 then
strval = strval + " SilentExport"
cflags = cflags-2097152
endif
if cflags and &H00400000 then
strval = strval + " BrowserPreferred"
cflags = cflags-4194304
endif
if cflags and &H00800000 then
strval = strval + " [H00800000]"
cflags = cflags-8388608
endif
if cflags and &H01000000 then
strval = strval + " [H01000000]"
cflags = cflags-16777216
endif
if cflags and &H02000000 then
strval = strval + " [H02000000]"
cflags = cflags-33554432
endif
if cflags and &H10000000 then
strval = strval + " Preferred"
cflags = cflags-268435456
endif
if cflags <> 0 then
strval = strval + " !!! ATTENTION: unsupported flag ["+cflags+"] detected !!!"
endif
flags_int2str = strval
end function
Function FindInArrayAdd(sName$, nameArray) As Integer
Dim i As Integer
For i = LBound(nameArray()) To UBound(nameArray())

 'Print nameArray(i) & " and " & sName
If nameArray(i) = sName Then
FindInArrayAdd = i
Exit Function
End If
Next
i = UBound(nameArray()) + 1
FindInArrayAdd = i
End Function
sub FinalFormat(oDoc)
rem ----------------------------------------------------------------------
rem define variables
Dim document as object
Dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document = oDoc.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem ----------------------------------------------------------------------
Dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "ToPoint"
args1(0).Value = "$A$1"
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())
rem ----------------------------------------------------------------------
Dim args2(1) as new com.sun.star.beans.PropertyValue
args2(0).Name = "By"
args2(0).Value = 1
args2(1).Name = "Sel"
args2(1).Value = true
dispatcher.executeDispatch(document, ".uno:GoRightToEndOfData", "", 0, args2())
rem ----------------------------------------------------------------------
Dim args3(2) as new com.sun.star.beans.PropertyValue
args3(0).Name = "FontHeight.Height"
args3(0).Value = 12
args3(1).Name = "FontHeight.Prop"
args3(1).Value = 100
args3(2).Name = "FontHeight.Diff"
args3(2).Value = 0
dispatcher.executeDispatch(document, ".uno:FontHeight", "", 0, args3())
rem ----------------------------------------------------------------------
Dim args4(0) as new com.sun.star.beans.PropertyValue
args4(0).Name = "Bold"
args4(0).Value = true
dispatcher.executeDispatch(document, ".uno:Bold", "", 0, args4())

rem ----------------------------------------------------------------------
Dim args5(0) as new com.sun.star.beans.PropertyValue
args5(0).Name = "HorizontalAlignment"
args5(0).Value = com.sun.star.table.CellHoriJustify.CENTER
dispatcher.executeDispatch(document, ".uno:HorizontalAlignment", "", 0, args5())
rem ----------------------------------------------------------------------
Dim args6(1) as new com.sun.star.beans.PropertyValue
args6(0).Name = "By"
args6(0).Value = 1
args6(1).Name = "Sel"
args6(1).Value = true
dispatcher.executeDispatch(document, ".uno:GoDownToEndOfData", "", 0, args6())
rem ----------------------------------------------------------------------
Dim args7(0) as new com.sun.star.beans.PropertyValue
args7(0).Name = "aExtraWidth"
args7(0).Value = 254
dispatcher.executeDispatch(document, ".uno:SetOptimalColumnWidth", "", 0, args7())
rem ----------------------------------------------------------------------
Dim args8(8) as new com.sun.star.beans.PropertyValue
args8(0).Name = "ByRows"
args8(0).Value = true
args8(1).Name = "HasHeader"
args8(1).Value = true
args8(2).Name = "CaseSensitive"
args8(2).Value = false
args8(3).Name = "IncludeAttribs"
args8(3).Value = true
args8(4).Name = "UserDefIndex"
args8(4).Value = 0
args8(5).Name = "Col1"
args8(5).Value = 7
args8(6).Name = "Ascending1"
args8(6).Value = true
args8(7).Name = "Col2"
args8(7).Value = 1
args8(8).Name = "Ascending2"
args8(8).Value = true
dispatcher.executeDispatch(document, ".uno:DataSort", "", 0, args8())
dispatcher.executeDispatch(document, ".uno:GoToCell", "", 0, args1())
end sub