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 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd">
<script:module xmlns:script="http://openoffice.org/2000/script" script:name="HandyTools" script:language="StarBasic" script:moduleType="normal">REM ***** BASIC *****
Option Explicit
Function GetFriendlyWords() as Variant
GetFriendlyWords = Array( _
"AreaCodeDesc", "Area", _
"AreaDescription", "Area", _
"ConsumerNumber", "ID", _
"ConsumerName", "Name", _
"MobileNumber", "Mobile", _
"BookDate", "Book"_
)
If (UBound(GetFriendlyWords) Mod 2) <> 1 Then
Print "Mismatch in friendlyWords array"
Exit Function
End If
End Function
Sub FormatRangeAsNumber(oSheet, oLocale, 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 = oFormats.queryKey(formatStr, oLocale, False)
' add formatStr if it doesn't exist
If formatNum = -1 Then
formatNum = oFormats.addNew(formatStr, oLocale)
If formatNum = -1 Then
MsgBox "Cannot add " & formatStr & " as NumberFormat", 0, "Fatal"
Exit Sub
End If
End If
With oReplace
.searchString = ".+"
.replaceString = "&"
.SearchRegularExpression = True
End With
oRange.NumberFormat = formatNum
oRange.replaceAll(oReplace)
End If
End Sub
Function GetColumnRange(oSheet, endColumn as Long, endRow as Long, searchString as String) as Object
Dim iHeaderPos
'GetColumn = -1
iHeaderPos = GetHeaderPosition(oSheet, endColumn, searchString)
If iHeaderPos = -1 Then
Exit Function
End If
GetColumnRange = oSheet.getCellRangeByPosition(iHeaderPos, 1, iHeaderPos, endRow)
End Function
Function RemoveColumns(oSheet, endColumn as Integer, columnNames) as Long
Dim columnName as String
Dim iHeader as Integer
RemoveColumns = endColumn
For Each columnName in columnNames
iHeader = GetHeaderPosition(oSheet, endColumn, columnName)
If iHeader <> -1 Then
oSheet.getColumns().removeByIndex(iHeader, 1)
endColumn = endColumn - 1
End If
Next
RemoveColumns = endColumn
End Function
Function RemoveColumnsExcept(oSheet as Object, endColumn as Integer, columnNames as Variant) as Long
Dim headerStr as String, columnName as String
Dim i% : i = 0
Dim rI% : rI = 0
Dim columnsToRemove(endColumn) as String
Dim headerRange, headerData
Dim found as Boolean : found = False
RemoveColumnsExcept = endColumn
headerRange = oSheet.getCellRangeByPosition(0, 0, 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
ReDim Preserve columnsToRemove(rI - 1)
RemoveColumnsExcept = RemoveColumns(oSheet, endColumn, columnsToRemove)
End Function
Sub ApplyTheme(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 = ThisComponent.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(oSheet) 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 = UsedRangeCursor(oSheet).Rows
For iRow = 0 To oRows.getCount() - 1
'Print rows(i).dbg_methods()
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
Sub ExportPDF(oSheet, exportFolder as String)
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
If Not IsValidFileName(oSheet.Name) Then
Exit Sub
End If
fileName = exportFolder & "/" & oSheet.Name & ".pdf"
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
With args(0) : .Name = "FilterName" : .Value = "calc_pdf_Export" : End With
With args(1) : .Name = "FilterData" : .Value = fd : End With
With args(2) : .Name = "Overwrite" : .Value = True : End With
ThisComponent.storeToURL(ConvertToUrl(fileName), args)
End Sub
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(ThisComponent, 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("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
Function UsedRangeCursor(Optional ByRef oSheet as Object) as Object
Dim cursor as Object
if IsNull(oSheet) Or IsMissing(oSheet) Then
oSheet = ThisComponent.getCurrentController().getActiveSheet()
End If
cursor = oSheet.createCursor()
cursor.gotoStartOfUsedArea(False)
cursor.gotoEndOfUsedArea(True)
UsedRangeCursor = cursor
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 as String
Dim friendlyWords : friendlyWords = GetFriendlyWords()
str = Trim(str)
' Check if Len(str) is really called multiple times
l = Len(str)
' Check with header "database"
For i = 0 To UBound(friendlyWords) Step 2
If friendlyWords(i) = str Then
UserFriendlyName = friendlyWords(i + 1)
Exit Function
End If
Next i
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(oSheet As Variant, endColumn as Integer, endRow as Integer, columnName as String)
Dim oRange as Object
Dim iHeaderPos as Integer
Dim oSortFields(1) as new com.sun.star.util.SortField
Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue
oRange = oSheet.getCellRangeByPosition(0, 1, endColumn, endRow)
ThisComponent.getCurrentController.select(oRange)
iHeaderPos = GetHeaderPosition(oSheet, endColumn, columnName)
If iHeaderPos = -1 Then
Exit Sub
End If
' Area
oSortFields(0).Field = iHeaderPos
oSortFields(0).SortAscending = True
' TODO Enable this later
' Date
'oSortFields(1).Field = 4
'oSortFields(1).SortAscending = True
oSortDesc(0).Name = "SortFields"
oSortDesc(0).Value = oSortFields
oRange.Sort(oSortDesc)
End Sub
Function NewSheet(sheetName as String) as Object
Dim sheets as Object
sheets = ThisComponent.Sheets()
If Not sheets.hasByName(sheetName) Then
sheets.insertNewByName(sheetName, sheets.getCount())
End If
NewSheet = sheets.getByName(sheetName)
End Function
Sub CleanColumnHeaders(oSheet as Object, endColumn as Integer)
Dim cell as Object
Dim neatName as String
Dim i as Integer
For i = 0 To endColumn
cell = oSheet.getCellByPosition(i, 0)
neatName = cell.getString()
neatName = UserFriendlyName(neatName)
cell.setString(neatName)
Next
End Sub
Sub RemoveExtraMergeCells(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 Integer
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)
ThisComponent.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
Dim document as Object
Dim dispatcher as Object
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
dispatcher.executeDispatch(document, ".uno:FreezePanes", "", 0, Array())
End Sub
Function GetHeaderPosition(ByRef oSheet as Object, endColumn as Integer, searchString as String) as Integer
Dim iColumn as Integer
Dim oCell as Object
Dim cellString as String
GetHeaderPosition = -1
If searchString = "" Then
Exit Function
End If
If roughHeaderMatch Then
searchString = UserFriendlyName(searchString)
End If
For iColumn = 0 To endColumn
oCell = oSheet.getCellByPosition(iColumn, 0)
cellString = oCell.String
If cellString = "" Then
'MsgBox "Cannot have empty column, endColumn is " & CStr(endColumn), 16, "Bad argument"
Exit Function
End If
If roughHeaderMatch Then
cellString = UserFriendlyName(cellString)
End If
If cellString = searchString OR Instr(cellString, searchString) = 1 Then
GetHeaderPosition = iColumn
Exit For
End If
Next iColumn
End Function
Function HighlightRowWithColumn(ByRef oSheet as Object, endColumn as Long, endRow as Long, highlightColumnName, highlightValue, removeColumn as Boolean, 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
HighlightRowWithColumn = endColumn
' Search for column position that has highlightBasedOn
iSearchColumn = GetHeaderPosition(oSheet, endColumn, highlightColumnName)
If iSearchColumn = -1 Then Exit Function
For i = 0 To endRow - 1
oCell = oSheet.getCellByPosition(iSearchColumn, i)
If InStr(oCell.getString(), highlightValue) > 0 Then
oCellRange = oSheet.getCellRangeByPosition(0, i, endColumn, i)
oCellRange.CellBackColor = highlightColor
End If
Next i
If removeColumn Then
oSheet.Columns.removeByIndex(iSearchColumn, 1)
endColumn = endColumn - 1
End If
End Function
Function FindHighestDateAsString(oSheet as Object, columnName as String, endColumn as Integer, endRow as Integer) as Date
Dim dateHeaderPos
Dim dateColumn
Dim dateVal
dateHeaderPos = GetHeaderPosition(oSheet, endColumn, columnName)
If dateHeaderPos = -1 Then
MsgBox "Cannot find a column header that starts with '" & columnName & "'", 0, "Bad column name"
Exit Function
End If
' TODO Check if the column we are searching, actually has date values.
dateColumn = oSheet.getCellRangeByPosition(dateHeaderPos, 1, dateHeaderPos, endRow)
dateVal = dateColumn.computeFunction(com.sun.star.sheet.GeneralFunction.MAX)
If dateVal = 0 Then MsgBox "Invalid date found in column '" & columnName & "' - " & dateHeaderPos & "", 16, "Bad date found"
FindHighestDateAsString = dateVal
End Function
' 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(oSheet as Object, 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 = 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 SetWidths(oSheet, endColumn as Integer, columnWidthArray() as Variant)
' columnWidthArray has values like Array(Array("Area", 0), Array("ID", 2000))
' 0 means autofill
Dim i as Integer
Dim columnWidth
Dim iHeaderColumn
For Each columnWidth in columnWidthArray
iHeaderColumn = GetHeaderPosition(oSheet, endColumn, columnWidth(0))
If iHeaderColumn = -1 Then
Print "Cannot find: " & columnWidth(0) & " in headers"
Exit Sub
End If
if columnWidth(1) = 0 Then
oSheet.getColumns().getByIndex(iHeaderColumn).OptimalWidth = True
Else
oSheet.getColumns().getByIndex(iHeaderColumn).Width = columnWidth(1)
End If
Next
End Sub
</script:module>