LibreOffice logo
BASEDOCUMENTER
The software tool for documenting your LibreOffice Base applications
 
Database file/home/jean-pierre/Documents/BaseDocumenter/www/databases/NorthWind/TT NorthWind.odb
File actual save date2018-08-01 13:54:50
Scanning done on2018-08-21 17:50:26
Documentation generated on2018-08-21 17:50:37
Table of contents
NorthWind
Procedures by module
Library Module name Procedure name Language Used by Number of code lines Procedure code
Standard _Init DBOpen Basic TT NorthWind.odb (Database) 15
Sub DBOpen(Optional poEvent As Object)
If GlobalScope.BasicLibraries.hasByName("Access2BaseDev") then
GlobalScope.BasicLibraries.LoadLibrary("Access2BaseDev")
ElseIf GlobalScope.BasicLibraries.hasByName("Access2Base") then
GlobalScope.BasicLibraries.LoadLibrary("Access2Base")
Else
MsgBox "Access2Base could not be found. Database could not be completely opened.", MB_OK + MB_EXCLAMATION, "Access2Base"
End If
If GlobalScope.BasicLibraries.hasByName("XrayTool") then GlobalScope.BasicLibraries.LoadLibrary("XrayTool")

REM =============================================================================================================================================================================

Call OpenConnection(ThisDatabaseDocument)

End Sub
Standard Browse BrowseThruControls Basic StartBrowseThruControls (Procedure) 19
Sub BrowseThruControls(poObject As Object, ByVal Optional piLevel As Integer)

Dim i As Integer, ocControl As Object
If IsMissing(piLevel) Then piLevel = 1
For i = 0 To poObject.Controls.Count - 1
Set ocControl = poObject.Controls(i)
Select Case ocControl.SubType
Case "SUBFORMCONTROL"
DebugPrint piLevel, ocControl.SubType, ocControl.Name
BrowseThruControls(ocControl.Form, piLevel + 1)
Case "GRIDCONTROL"
DebugPrint piLevel, ocControl.SubType, ocControl.Name
BrowseThruControls(ocControl, piLevel + 1)
Case Else
If ocControl.hasProperty("Value") Then DebugPrint piLevel, ocControl.SubType, ocControl.Name, ocControl.Value
End Select
Next i

End Sub
Standard Browse Main Basic   3
Sub Main
StartBrowseThruControls("Orders_Browse")
End Sub
Standard Browse StartBrowseThruControls Basic Main (Procedure) 7
Sub StartBrowseThruControls(ByVal psFormName As String)

Dim oMainForm As Object
Set oMainForm = Forms(psFormName)
BrowseThruControls(oMainForm)

End Sub
Standard CalculatedField ComputeOrderTotal Basic Orders_CalculatedField (Form) 14
Sub ComputeOrderTotal(poEvent As Object)
Dim oeEvent As Object, ofForm As Object, ocSum As Object, vOrderId As Variant

Set oeEvent = Events(poEvent)
If Not IsNull(oeEvent) Then
Set ofForm =oeEvent.Source
vOrderId = ofForm.Controls("OrderID").Value
If Not IsEmpty(vOrderId) Then
Set ocSum = ofForm.Controls("SumOfDetails")
ocSum.Value = DSum("[Order Details].[UnitPrice] * [Order Details].[Quantity] * (1 - [Order Details].[Discount])" _
, "[Order Details]", "[Order Details].[OrderID]=" & vOrderId)
End If
End If
End Sub
Standard CalculatedField ComputeOrderTotalGrid Basic   24
Sub ComputeOrderTotalGrid(poEvent As Object)
Dim oeEvent As Object, ofForm As Object, ocGrid As Object, ocOrderID As Object, ocSum As Object, vOrderId As Variant

Set oeEvent = Events(poEvent)
If Not IsNull(oeEvent) Then
Set ofForm =oeEvent.Source
Set ocGrid = ofForm.Controls("OrderDetails_Grid")
Set ocOrderId = ocGrid.Controls("OrderID")
vOrderId = ocOrderId.Value
Set ocSum = ocGrid.Controls("SumOfDetails")
'DebugPrint ocSum.Value
ocSum.Value = DSum("[Order Details].[UnitPrice] * [Order Details].[Quantity] * (1 - [Order Details].[Discount])" _
, "[Order Details]", "[Order Details].[OrderID]=" & vOrderId)
DebugPrint ocSum.Value
' xray ocgrid.controlmodel
With ocGrid.ControlModel
If .getRowSet().IsNew Then
.getRowSet().insertRow()
ElseIf .getRowSet.IsModified Then
.getRowSet().updateRow()
End If
End With
End If
End Sub
Standard Calculator CalcButtonPressed Basic dlgCalc|Cmd1 (Control)
dlgCalc|Cmd2 (Control)
dlgCalc|Cmd3 (Control)
dlgCalc|Cmd4 (Control)
dlgCalc|Cmd5 (Control)
dlgCalc|Cmd6 (Control)
dlgCalc|Cmd9 (Control)
dlgCalc| btnClear (Control)
dlgCalc|btnMult (Control)
dlgCalc|btnEnter (Control)
dlgCalc|btnSub (Control)
dlgCalc|btnDiv (Control)
dlgCalc|btnInvert (Control)
dlgCalc|Cmd0 (Control)
dlgCalc|btnPoint (Control)
dlgCalc|btnCE (Control)
dlgCalc|btnAdd (Control)
dlgCalc|Cmd7 (Control)
dlgCalc|Cmd8 (Control)
25
REM ========================================================================================================
Sub CalcButtonPressed(poEvent As Object)

Dim oEvent As Object, sName As String, oButton As Object, oDisplay As Object, sChar As String
Set oEvent = Application.Events(poEvent)
If oEvent.EventType <> "ACTIONEVENT" Then Exit Sub

Set oButton = oEvent.Source
sName = UCase(oButton.Name)
Select Case sName
Case "BTNADD" : sChar = "+"
Case "BTNSUB" : sChar = "-"
Case "BTNMULT" : sChar = "*"
Case "BTNDIV" : sChar = "/"
Case "BTNENTER" : sChar = "="
Case "BTNCLEAR" : sChar = "C"
Case "BTNCE" : sChar = "CE"
Case "BTNINVERT" : sChar = "1/x"
Case "BTNPOINT" : sChar = "."
Case Else : sChar = Right(sName, 1) ' DIGIT !!
End Select
Call ProcessKey(sChar)
Exit Sub

End Sub
Standard Calculator CalcKeyPressed Basic dlgCalc|CalcDisplay (Control) 36
REM ========================================================================================================
Sub CalcKeyPressed(poEvent As Object)

Dim oEvent As Object, oDisplay As Object, sChar As String
Set oEvent = Application.Events(poEvent)
If oEvent.EventType <> "KEYEVENT" Then Exit Sub

'Accepted keys: 0-9, BACKSPACE, C, ESCAPE, dot, comma, +, -, *, /, %, =, ENTER.
'All other keys ignored
With oEvent
Select Case True ' Both KeyCode and KeyChar used to be generic across all keyboards and OS's
Case .KeyAlt, .KeyCtrl : Beep : Exit Sub ' Cancel if associated with Alt or Ctrl
Case .KeyCode = com.sun.star.awt.Key.ESCAPE Or UCase(.KeyChar) = "C" : sChar = "C"
Case .KeyCode = com.sun.star.awt.Key.BACKSPACE : sChar = "CE"
Case .KeyCode = com.sun.star.awt.Key.RETURN Or .KeyCode = com.sun.star.awt.Key.EQUAL Or .KeyChar = "="
sChar = "="
Case .KeyCode = com.sun.star.awt.Key.ADD Or .KeyChar = "+" : sChar = "+"
Case .KeyCode = com.sun.star.awt.Key.SUBTRACT Or .KeyChar = "-" : sChar = "-"
Case .KeyCode = com.sun.star.awt.Key.MULTIPLY Or .KeyChar = "*" : sChar = "*"
Case .KeyCode = com.sun.star.awt.Key.DIVIDE Or .KeyChar = "/" Or .KeyChar = ":"
sChar = "/"
Case .KeyChar = "_" : sChar = "1/x"
Case .KeyCode = com.sun.star.awt.Key.DECIMAL Or .KeyCode = com.sun.star.awt.Key.POINT _
Or .KeyCode = com.sun.star.awt.Key.COMMA Or .KeyChar = "." Or .KeyChar = ","
sChar = "."
Case .KeyChar >= "0" And .KeyChar <= "9" : sChar = .KeyChar
Case .KeyCode >= com.sun.star.awt.Key.NUM0 And .KeyCode <= com.sun.star.awt.Key.NUM9
sChar = Trim(Str(.KeyCode - com.sun.star.awt.Key.NUM0))
Case Else : Beep : Exit Sub
End Select
End With

Call ProcessKey(sChar)
Exit Sub

End Sub
Standard Calculator ProcessKey Basic CalcButtonPressed (Procedure)
CalcKeyPressed (Procedure)
107
REM ========================================================================================================
Sub ProcessKey(ByVal psChar As String)
' Process gCalc structure based on argument

Dim sDisplayText As String
Const cstMax = 999999999999

Select Case psChar
Case "C" ' Cancel
gCalc.DisplayText = Format(0, "0.")
gCalc.Operand1 = 0
gCalc.Operand2 = 0
gCalc.NumberOfOperands = 0
gCalc.PendingOperation = " "
gCalc.LastInput = "NONE"
Case "CE" ' Cancel entry
gCalc.DisplayText = Format(0, "0.")
gCalc.DecimalPoint = False
gCalc.LastInput = "CE"
Case "." ' Decimal point
' If last keypress was an operator, initialize DisplayText to "0."
' Otherwise, append a decimal point to the display.
If gCalc.DecimalPoint Then
Beep
Else
If gCalc.LastInput = "NEG" Then
gCalc.DisplayText = Format(0, "-0.")
ElseIf gCalc.LastInput <> "NUMS" Then
gCalc.DisplayText = Format(0, "0.")
End If
gCalc.DecimalPoint = True
gCalc.LastInput = "NUMS"
End If
Case "+", "-", "*", "/", "=" ' Arithmetic operators
' If the immediately preceeding keypress was part of a number, increment DecimalPoint. If one operand is present,
' set Operand1. If two are present, set Operand1 equal to the result of the operation on Operand1 and the current
' input string, and display the result.
sDisplayText = gCalc.DisplayText
If gCalc.LastInput = "NUMS" Then
gCalc.NumberOfOperands = gCalc.NumberOfOperands + 1
End If
Select Case gCalc.NumberOfOperands
Case 0
If psChar = "-" And gCalc.LastInput <> "NEG" Then
gCalc.DisplayText = "-" & gCalc.DisplayText
gCalc.LastInput = "NEG"
End If
Case 1
gCalc.Operand1 = Val(gCalc.DisplayText)
If psChar = "-" And gCalc.LastInput <> "NUMS" And gCalc.PendingOperation <> "=" Then
gCalc.DisplayText = "-"
gCalc.LastInput = "NEG"
End If
Case 2
gCalc.Operand2 = Val(sDisplayText)
Select Case gCalc.PendingOperation
Case "+"
gCalc.Operand1 = gCalc.Operand1 + gCalc.Operand2
Case "-"
gCalc.Operand1 = gCalc.Operand1 - gCalc.Operand2
Case "*"
gCalc.Operand1 = gCalc.Operand1 * gCalc.Operand2
Case "/"
If Sgn(gCalc.Operand2) = 0 Then
gCalc.Operand1 = cstMax * Sgn(gCalc.Operand1)
Else
gCalc.Operand1 = gCalc.Operand1 / gCalc.Operand2
End If
Case "="
gCalc.Operand1 = gCalc.Operand2
End Select
gCalc.DisplayText = Join(Split(Format(gCalc.Operand1, cstStdFormat), ","), ".")
gCalc.NumberOfOperands = 1
End Select
If gCalc.LastInput <> "NEG" Then
gCalc.LastInput = "OPS"
gCalc.PendingOperation = psChar
End If
Case "1/x" ' Invert result
If gCalc.LastInput = "NUMS" Then gCalc.Operand1 = Val(gCalc.DisplayText)
If Sgn(gCalc.Operand1) = 0 Then
gCalc.Operand1 = cstMax
Else
gCalc.Operand1 = 1 / gCalc.Operand1
End If
gCalc.LastInput = "OPS"
gCalc.DisplayText = Join(Split(Format(gCalc.Operand1, cstStdFormat), ","), ".")
Case Else ' DIGIT
' Append new number to the number in the display.
If gCalc.LastInput <> "NUMS" Then
gCalc.DisplayText = Format(0, ".")
gCalc.DecimalPoint = False
End If
If gCalc.DecimalPoint Then
gCalc.DisplayText = gCalc.DisplayText & psChar
Else
gCalc.DisplayText = Left(gCalc.DisplayText, InStr(gCalc.DisplayText, ".") - 1) & psChar & "."
End If
If gCalc.LastInput = "NEG" Then gCalc.DisplayText = "-" & gCalc.DisplayText
gCalc.LastInput = "NUMS"
End Select

'DebugPrint psChar, gCalc.Operand1, gCalc.Operand2, gCalc.PendingOperation, gCalc.NumberOfOperands, gCalc.LastInput, gCalc.DisplayText
gCalc.DisplayField.Value = Join(Split(gCalc.DisplayText, "."), gcalc.LocalePoint)
Exit Sub

End Sub
Standard Calculator StartCalcDialog Basic StartCalculator (Procedure) 73
REM ========================================================================================================
Sub StartCalcDialog(poEvent, ByVal psFieldName As String, Optional ByVal pbCopy As Boolean)

Dim ocFieldToCompute As Object, ocButton As Object, ofForm As Object, oDialog As Object
Dim i As Integer, bFound As Boolean, iDialog As Integer

If IsMissing(pbCopy) Then pbCopy = True

If IsNull(poEvent) Then
pbCopy = False
Else
Set ocButton = Application.Events(poEvent).Source
If ocButton.ObjectType <> "CONTROL" Then Exit Sub
'Check field name exists
Set ofForm = ocButton.Parent ' ofForm could be a form or a subform !
bFound = False
For i = 0 To ofForm.Controls().Count - 1
Set ocFieldToCompute = ofForm.Controls(i)
If UCase(ocFieldToCompute.Name) = UCase(psFieldName) Then
bFound = True
Exit For
End If
Next i
If Not bFound Then
TraceLog("ERROR", "Field name " & psFieldName & " not found in form or subform " & ofForm.Name)
Exit Sub
End If

'Check field is of admitted types
If ocFieldToCompute.SubType <> "NUMERICFIELD" And ocFieldToCompute.SubType <> "CURRENCYFIELD" Then
TraceLog("ERROR", "Field " & psFieldName & " is not numeric")
Exit Sub
End If
End If

Const dlgOK = 1 ' OK button pressed
Const dlgCancel = 0 ' Cancel button pressed
Set oDialog = Application.AllDialogs("dlgCalc")
oDialog.Start

' Initialize gCalc
gCalc.DisplayField = oDialog.Controls("CalcDisplay")
gCalc.LocalePoint = Right(Format(0,"General Number"),1)
If pbCopy Then
gCalc.Operand1 = ocFieldToCompute.Value
gCalc.Operand2 = gCalc.Operand1
gCalc.DisplayText = Join(Split(Format(gCalc.Operand1, cstStdFormat), ","), ".")
gCalc.DecimalPoint = ( Abs(gCalc.Operand1 - Fix(gCalc.Operand1)) > 0 )
gCalc.NumberOfOperands = 1
gCalc.LastInput = "OPS"
gCalc.PendingOperation = "="
Else
gCalc.LastInput = "NONE"
gCalc.NumberOfOperands = 0
gCalc.PendingOperation = " "
gCalc.DecimalPoint = False
gCalc.Operand1 = 0
gCalc.Operand2 = 0
End If

'Load dialog
gCalc.DisplayField.Value = Format(gCalc.Operand1, cstStdFormat)
oDialog.Controls("BtnPoint").Caption = gCalc.LocalePoint ' Set decimal point button to locale setting
iDialog = oDialog.Execute
Select Case iDialog
Case dlgOK
If Not IsNull(poEvent) Then ocFieldToCompute.Value = gCalc.Operand1
Case dlgCancel
End Select

oDialog.Terminate
Exit Sub
End Sub
Standard Calculator StartCalculator Basic Calculator|StartCalc (Control) 12
Sub StartCalculator(Optional poEvent As Object)
' StartCalculator should be adapted to user's need:
' - it is assumed to be activated from an appropriate button
' - the field to compute is assumed in the same form or subform as the button
' - the field to compute must be of type NUMERICFIELD or CURRENCYFIELD
' - the name of the field to compute should be set in next line
' - The 3rd argument is optional. True = initialize calculator with field current value

If IsMissing(poEvent) Then poEvent = Nothing
Call Calculator.StartCalcDialog(poEvent, "TargetCalcField", True)

End Sub
Standard ComboBox Update2ndCombo Basic Orders_2Combos|EmployeeCity (Control) 10
Sub Update2ndCombo(poEvent As Object)

Dim ocCombo1 As Object, ocCombo2 As Object, sSQL As String
Set ocCombo1 = Events(poEvent).Source
Set ocCombo2 = ocCombo1.Parent.Controls("EmployeeName")
sSQL = "SELECT DISTINCT [LastName] FROM [Employees] WHERE [Employees].[City]='" & ocCombo1.Value & "'"
ocCombo2.RowSourceType = com.sun.star.form.ListSourceType.SQL
ocCombo2.RowSource = sSQL

End Sub
Standard ComboBox UpdateMainForm Basic Orders_2Combos|EmployeeName (Control) 10
Sub UpdateMainForm(poEvent As Object)

Dim ofForm As Object, ocCombo As Object, sSQL As String, lEmpID As Integer
Set ocCombo = Events(poEvent).Source
Set ofForm = ocCombo.Parent
lEmpID = DLookup("[EmployeeID]", "[Employees]", "[LastName]='" & ocCombo.Value & "'")
ofForm.Filter = "[EmployeeID]=" & lEmpID
ofForm.FilterOn = True

End Sub
Standard CrossTab AliasOf Basic MakeCrossTab (Procedure) 5
Function AliasOf(ByVal psString As String) As String
Dim iPos As Integer
iPos = InStr(psString, " AS ")
If iPos > 0 Then AliasOf = Right(psString, Len(psString) - iPos - 3) Else AliasOf = psString
End Function
Standard CrossTab Main Basic   38
Sub Main()
Dim sSql As String
' sSql = MakeCrossTab( _
' "[FirstName] || ' ' || [LastName] As [Name]" _
' , "Year([OrderDate]) As [Year]" _
' , "Count(*)" _
' , "[Employees] INNER JOIN [Orders] ON ([Employees].[EmployeeID]=[Orders].[EmployeeID])" _
' , "DESC" _
' )
' sSql = MakeCrossTab( _
' "[FirstName] || ' ' || [LastName] As [Name]" _
' , "YEAR([OrderDate]) || 'Q' || QUARTER([OrderDate]) As [Month]" _
' , "Count(*)" _
' , "[Employees] INNER JOIN [Orders] ON ([Employees].[EmployeeID]=[Orders].[EmployeeID])" _
' , "DESC" _
' )
' sSql = MakeCrossTab( _
' "[FirstName] || ' ' || [LastName] As [Name]" _
' , "YEAR([OrderDate]) || '-' || RIGHT('0' || MONTH([OrderDate]), 2) As [Month]" _
' , "Count(*)" _
' , "[Employees] INNER JOIN [Orders] ON ([Employees].[EmployeeID]=[Orders].[EmployeeID])" _
' , "DESC" _
'
' )
sSql = MakeCrossTab( _
"[Customers].[CompanyName] As [Customer], [Products].[ProductName] AS [Name]" _
, "YEAR([OrderDate]) || 'Q' || QUARTER([OrderDate]) As [Quarter]" _
, "SUM([Order Details].[UnitPrice]*[Quantity]*(1-[Discount]))" _
, "[Order Details], [Products], [Orders], [Customers] " _
& "WHERE [Order Details].[ProductID] = [Products].[ProductID] " _
& "AND [Order Details].[OrderID] = [Orders].[OrderID] " _
& "AND [Customers].[CustomerID] = [Orders].[CustomerID] " _
& "AND YEAR([Orders].[OrderDate]) = 1997" _
, "[Customer]" _
)
' OpenSQL(sSql, dbSQLPassThrough)
CurrentDb().CreateQueryDef("Query1", sSql, dbSQLPassThrough)
End Sub
Standard CrossTab MakeCrossTab Basic Main (Procedure) 82
Public Function MakeCrossTab( _
Byval psRowHeading As String _
, Byval psColHeading As String _
, Byval psAggregate As String _
, Byval psFromExpression As String _
, Byval psSortBy As String _
) As String
REM ===========================================================================================
'Build SQL
'---------
' SELECT
' [RowheadingAlias(0)],
' [RowheadingAlias(1)],
' ...
' SUM( CASE [ColHeadingAlias] WHEN 'ColValue0' THEN [Data] ELSE 0 END ) As [ColValue0],
' SUM( CASE [ColHeadingAlias] WHEN 'ColValue1' THEN [Data] ELSE 0 END ) As [ColValue1],
' SUM( CASE [ColHeadingAlias] WHEN 'ColValue2' THEN [Data] ELSE 0 END ) As [ColValue2],
' ...
' SUM( [Data] ) As [All]
' FROM
' (SELECT RowHeading(0),
' RowHeading(1),
' ...
' ColHeading,
' Aggregate As [Data]
' FROM FromExpression
' GROUP BY RowHeadingAlias(0),RowHeadingAlias(1), ColHeadingAlias
' )
' GROUP BY RowHeadingAlias(0),RowHeadingAlias(1)
' ORDER BY [All] OrderBy
REM ===========================================================================================

Dim sQuery As String, sSubQuery As String, vRowHeading() As Variant, sGroupBy As String, sSortBy As String
Dim sDataQuery As String, oData As Object, oField As Object, sCase As String, sValue As String
Dim i As Integer

vRowHeading() = Split(psRowHeading, ",")
If UBound(vRowHeading) < 0 Then Exit Function

' SUBQUERY
sSubQuery = "SELECT " & vRowHeading(0)
For i = 1 To UBound(vRowHeading)
sSubQuery = sSubQuery & "," & vRowheading(i)
Next i
sSubQuery = sSubQuery & ", " & psColHeading & ", " & psAggregate & " AS [Data] FROM " & psFromExpression & " GROUP BY "
sGroupBy = AliasOf(vRowHeading(0))
For i = 1 To UBound(vRowHeading)
sGroupBy = sGroupBy & ", " & AliasOf(vRowHeading(i))
Next i
sSubQuery = sSubQuery & sGroupBy & "," & AliasOf(psColHeading)

' MAIN QUERY
' Identify all distinct column headings
sDataQuery = "SELECT DISTINCT " & psColHeading & " FROM " & psFromExpression & " ORDER BY " & AliasOf(psColHeading)
Set oData = CurrentDb().OpenRecordset(sDataQuery,, dbSQLPassThrough, dbReadOnly)
Set oField = oData.Fields(0)
' Build CASE sentences
sCase = ""
For i = 0 To UBound(vRowHeading)
scase = sCase & AliasOf(vRowHeading(i)) & ", "
Next i
With oData ' Recordset
Do While Not .EOF
sValue = CStr(oField.Value) ' Force string
sCase = sCase & "SUM( CASE " & AliasOf(psColHeading) & " WHEN '" & sValue & "' THEN [Data] ELSE 0 END ) As [" & sValue & "],"
.MoveNext
Loop
.mClose()
End With
sCase = sCase & "SUM( [Data] ) As [All]"
' Final query
Select Case UCase(psSortBy)
Case "", "ASC" : sSortBy = "ORDER BY [All] ASC"
Case "DESC" : sSortBy = "ORDER BY [All] DESC"
Case Else : sSortBy = "ORDER BY " & psSortBy
End Select
sQuery = "SELECT " & sCase & " FROM (" & sSubQuery & ") GROUP BY " & sGroupBy & sSortBy

' Store SQL
MakeCrossTab = sQuery

End Function
Standard Dictionary LongStr Basic ScanTables (Procedure)
ScanSchema (Procedure)
4
Function LongStr(psString As String) As String
Const cstLength = 20
LongStr = Left(psString & Space(cstLength), cstLength)
End Function
Standard Dictionary ScanSchema Basic   20
Sub ScanSchema()

Dim oRecordset As Object, sSql As String
sSql = "SELECT [TABLE_NAME],[COLUMN_NAME],[SYSTEM_COLUMNS].[TYPE_NAME],[COLUMN_SIZE] " _
& "FROM [INFORMATION_SCHEMA].[SYSTEM_TABLES],[INFORMATION_SCHEMA].[SYSTEM_COLUMNS] " _
& "WHERE [TABLE_SCHEM]='PUBLIC' AND [SYSTEM_COLUMNS].[TABLE_NAME]=[SYSTEM_TABLES].[TABLE_NAME]"

Set oRecordset = Application.CurrentDb().OpenRecordset(sSql, , dbSQLPassThrough, dbReadOnly)
With oRecordset
iNbFields = .Fields.Count
Do While Not .EOF()
DebugPrint LongStr(.Fields("TABLE_NAME").Value) _
, LongStr(.Fields("COLUMN_NAME").Value) _
, LongStr(.Fields("TYPE_NAME").Value) _
, .Fields("COLUMN_SIZE").Value
.MoveNext()
Loop
End With

End Sub
Standard Dictionary ScanSchemaSQL Basic   9
Sub ScanSchemaSQL()

Dim sSql As String
sSql = "SELECT [TABLE_NAME],[COLUMN_NAME],[SYSTEM_COLUMNS].[TYPE_NAME],[COLUMN_SIZE] " _
& "FROM [INFORMATION_SCHEMA].[SYSTEM_TABLES],[INFORMATION_SCHEMA].[SYSTEM_COLUMNS] " _
& "WHERE [TABLE_SCHEM]='PUBLIC' AND [SYSTEM_COLUMNS].[TABLE_NAME]=[SYSTEM_TABLES].[TABLE_NAME]"
OpenSQL(sSql, dbSQLPassThrough)

End Sub
Standard Dictionary ScanTables Basic   18
Sub ScanTables()

Dim oDatabase As Object, oTable As Object, oField As Object
Dim i As Integer, j As Integer

Set oDatabase = Application.CurrentDb()
With odatabase
For i = 0 To .TableDefs.Count - 1
Set oTable = .TableDefs(i)
DebugPrint oTable.Name
For j = 0 To oTable.Fields.Count - 1
Set oField = oTable.Fields(j)
DebugPrint "", LongStr(oField.Name), LongStr(oField.TypeName), oField.Size
Next j
Next i
End With

End Sub
Standard Export AppendToFile Basic   5
Public Property Let AppendToFile(blnAppend As Boolean)
'optional
'will append to existing export file instead of overwriting it
bAppend = blnAppend
End Property
Standard Export ArrBoundsCheck Basic ExportSource (Procedure) 13
Private Function ArrBoundsCheck(varExport As Variant) As Boolean
'the array has to be 2-dimensional
On Error Resume Next
Dim varTemp As Variant

varTemp = varExport(LBound(varExport, 1), LBound(varExport, 2))
If Err.Number = 0 Then
ArrBoundsCheck = True
Else
Err.Clear
End If

End Function
Standard Export Class_Initialize Basic   39
Private Sub Class_Initialize()
On Error GoTo 0

'If Access Then
'' Dim ref As Access.Reference
Dim blnDAOReferenced As Boolean, blnBroken As Boolean

Const cDAOGUID As String = "{00025E01-0000-0000-C000-000000000046}"

iErrHandling = Application.GetOption("Error Trapping")
Application.SetOption "Error Trapping", 2

For Each ref In Application.References
On Error Resume Next
blnBroken = ref.IsBroken
If VBA.Err Then blnBroken = True
On Error GoTo 0
If ref.Name = "DAO" And ref.Kind = 0 And VBA.StrComp(ref.Guid, cDAOGUID, 1) = 0 And Not blnBroken Then
blnDAOReferenced = True
Exit For
End If
Next ref
Set ref = Nothing

If Not blnDAOReferenced Then _
Err.Raise ERR_BAD_DAO_REFERENCE, "TextExport::Initialize", "A reference to DAO has to be set."
'End If

'defaults
sTextQualifier = VBA.Chr(34)
sFieldDelimiter = VBA.vbTab
sRecDelimiter = VBA.vbCrLf
sReplaceWith = " "
sExportType = "ASCII"
bIncludeFieldNames = True
mAL.ColumnDimension = 1
mAL.RowDimension = 2

End Sub
Standard Export Class_Terminate Basic   18
Private Sub Class_Terminate()

If Not oExport Is Nothing Then
oExport.Close 'either a clone or has been opened in the class
Set oExport = Nothing
End If

If Not odbCurrent Is Nothing Then Set odbCurrent = Nothing

Close iFileNumber

Call SysCmd(acSysCmdClearStatus)

'If Access Then
Application.SetOption "Error Trapping", iErrHandling
'End If

End Sub
Standard Export ExcludeFields Basic   10
Public Property Let ExcludeFields(strExcludeFields As String)
'optional, .-delimited string of fields to exclude
'ignored for arrays

If Not strExcludeFields Like "[!.]*?." Then _
Err.Raise ERR_INVALID_EXCLUDE_LIST, "TextExport::ExcludeFields", "Invalid exclude field list format."

sExcludeFields = strExcludeFields

End Property
Standard Export Export Basic   16
Public Function Export(Optional blnTransposeArray As Boolean) As Boolean
'wrapper for ExportRs or ExportArr

If Not IsEmpty(vExport) Then
If blnTransposeArray Then
mAL.ColumnDimension = 2
mAL.RowDimension = 1
End If
Export = ExportArr
ElseIf Not oExport Is Nothing Then
Export = ExportRs
Else
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::Export", "Invalid export source."
End If

End Function
Standard Export ExportArr Basic Export (Procedure) 79
Private Function ExportArr() As Boolean
'1st dimension - "columns", 2nd dimension - "rows"
'or the other way when transposed (Me.Export(True))
On Error GoTo Err_Handler
Dim strHeader As String, strRecord As String
Dim lngRowCount As Long, lngColumnCount As Long
Dim lngTotalRows As Long
Dim varElement As Variant
Dim lngFilePos As Long

If sExportType = "WP" Then
sTextQualifier = vbNullString
sFieldDelimiter = Chr(18) & Chr(10)
sRecDelimiter = Chr(5) & Chr(10)
strHeader = Chr(255) & "WPC^" & String$(3, vbNullChar) & Chr(1) & Chr(10) & String$(6, vbNullChar) & Chr(251) & Chr(255) _
& Chr(5) & vbNullChar & "2" & String$(5, vbNullChar) & Chr(6) & vbNullChar & Chr(8) & String$(3, vbNullChar) & "B" & String$(3, vbNullChar) _
& Chr(8) & vbNullChar & Chr(2) & String$(3, vbNullChar) & "J" & String$(3, vbNullChar) & Chr(1) & vbNullChar _
& Chr(18) & String$(3, vbNullChar) & "L" & String$(13, vbNullChar) & Chr(8) & vbNullChar & "|" _
& vbNullChar & "x" & String$(5, vbNullChar) & Format$(Now, "mmm dd, yyyy") & String$(6, vbNullChar)
End If

iFileNumber = FreeFile
Open sExportFilename For Binary Access Write Lock Write As iFileNumber

If bAppend Then _
lngFilePos = LOF(iFileNumber)

Put 'iFileNumber, lngFilePos + 1, strHeader 'wrote header, if any

Call SysCmd(acSysCmdSetStatus, "Opening source...")
lngTotalRows = UBound(vExport, mAL.RowDimension) - LBound(vExport, mAL.RowDimension) + 1
If lngTotalRows > 0 Then
Call SysCmd(acSysCmdClearStatus)
Call SysCmd(acSysCmdInitMeter, "Exporting text...", lngTotalRows)
End If

lExportedCount = 0
For lngRowCount = LBound(vExport, mAL.RowDimension) To UBound(vExport, mAL.RowDimension)
Call SysCmd(acSysCmdUpdateMeter, lngRowCount)
strRecord = vbNullString
For lngColumnCount = LBound(vExport, mAL.ColumnDimension) To UBound(vExport, mAL.ColumnDimension)
If mAL.ColumnDimension = 2 And mAL.RowDimension = 1 Then 'transposed
varElement = vExport(lngRowCount, lngColumnCount)
Else
varElement = vExport(lngColumnCount, lngRowCount)
End If
Select Case VarType(varElement)
Case vbString
If Len(sTextQualifier) > 0 Then
strRecord = strRecord & sTextQualifier & ReplaceStr(CStr(varElement), sTextQualifier, sTextQualifier & sTextQualifier) & sTextQualifier & sFieldDelimiter
Else 'make sure there's no field delimiters in text fields
strRecord = strRecord & ReplaceStr(CStr(varElement), sFieldDelimiter, sReplaceWith) & sFieldDelimiter
End If
Case vbEmpty, vbNull, vbInteger, vbLong, vbSingle, vbDouble, _
vbCurrency, vbDate, vbBoolean, vbDecimal, vbByte
strRecord = strRecord & Nz(varElement, vbNullString) & sFieldDelimiter
Case Else 'unexportable element, shouldn't happen (supposed to be validated previously)
Err.Raise ERR_INVALID_EXPORT_ARRAY, "TextExport::ExportSource", "Invalid export array."
End Select
Next lngColumnCount
strRecord = ReplaceStr(strRecord, sRecDelimiter, sReplaceWith) 'make sure there's no record delimiters in records
strRecord = LeftstrRecordrd, Len(strRecord) - Len(sFieldDelimiter)) & sRecDelimiter
Put 'iFileNumber, , strRecord
lExportedCount = lExportedCount + 1
Next lngRowCount

ExportArr = True

Exit_Here:
On Error Resume Next
Close iFileNumber
Call SysCmd(acSysCmdClearStatus)
Exit Function

Err_Handler:
Err.Raise Err.Number, Err.Source, Err.Description
Resume Exit_Here

End Function
Standard Export ExportDatabase Basic   5
Public Property Let ExportDatabase(db As Object)'DAO.Database)
'required if ExportSource is a table name, a query name, or a SQL statement
'no default
Set odbCurrent = db
End Property
Standard Export ExportFilename Basic   14
Public Property Let ExportFilename(strExpFilename As String)
'required
On Error GoTo 0
Dim intFileNumber As Integer

If Not bAppend Or Not FileExists(strExpFilename) Then
intFileNumber = FreeFile
Open strExpFilename For Output Access Write Lock Read Write As intFileNumber
Close intFileNumber 'set to 0-length/create a 0-length
End If

sExportFilename = strExpFilename

End Property
Standard Export ExportRs Basic Export (Procedure) 104
Private Function ExportRs() As Boolean
On Error GoTo Err_Handler
Dim strHeader As String, strRecord As String
Dim intCount As Integer
Dim fld As DAO.Field
Dim lngFilePos As Long

If Not oExport.Fields.Count > 0 Then _
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::Export", "Invalid export source."

If sExportType = "WP" Then
sTextQualifier = vbNullString
sFieldDelimiter = Chr(18) & Chr(10)
sRecDelimiter = Chr(5) & Chr(10)
strHeader = Chr(255) & "WPC^" & String$(3, vbNullChar) & Chr(1) & Chr(10) & String$(6, vbNullChar) & Chr(251) & Chr(255) _
& Chr(5) & vbNullChar & "2" & String$(5, vbNullChar) & Chr(6) & vbNullChar & Chr(8) & String$(3, vbNullChar) & "B" & String$(3, vbNullChar) _
& Chr(8) & vbNullChar & Chr(2) & String$(3, vbNullChar) & "J" & String$(3, vbNullChar) & Chr(1) & vbNullChar _
& Chr(18) & String$(3, vbNullChar) & "L" & String$(13, vbNullChar) & Chr(8) & vbNullChar & "|" _
& vbNullChar & "x" & String$(5, vbNullChar) & Format$(Now, "mmm dd, yyyy") & String$(6, vbNullChar)
End If

If bIncludeFieldNames Then
For intCount = 0 To oExport.Fields.Count - 1
If Not (InStr(1, sExcludeFields, oExport.Fields(intCount).Name & ".", vbTextCompare) > 0) Then
strHeader = strHeader & sTextQualifier & ReplaceStr(oExport.Fields(intCount).Name, sRecDelimiter, sReplaceWith) & sTextQualifier & sFieldDelimiter
End If
Next intCount
strHeader = LeftstrHeaderer, Len(strHeader) - Len(sFieldDelimiter)) & sRecDelimiter
End If

iFileNumber = FreeFile
Open sExportFilename For Binary Access Write Lock Write As iFileNumber

If bAppend Then _
lngFilePos = LOF(iFileNumber)

Put 'iFileNumber, lngFilePos + 1, strHeader 'wrote header, if any

With oExport
Call SysCmd(acSysCmdSetStatus, "Opening source...")
If oExport.RecordCount > 0 Then
.MoveLast 'to get accurate progress bar
Call SysCmd(acSysCmdClearStatus)
.MoveFirst
Call SysCmd(acSysCmdInitMeter, "Exporting text...", 100)
End If
lExportedCount = 0
Do Until .EOF
Call SysCmd(acSysCmdUpdateMeter, .PercentPosition)
strRecord = vbNullString
For intCount = 0 To .Fields.Count - 1
If Not (InStr(1, sExcludeFields, .Fields(intCount).Name & ".", vbTextCompare) > 0) Then
Set fld = .Fields(intCount)
Select Case fld.Type
Case dbText, dbMemo, dbChar
If Len(sTextQualifier) > 0 Then
If InStr(1, fld.Value, sTextQualifier, vbBinaryCompare) > 0 Then 'double text qualifiers
strRecord = strRecord & CStr(sTextQualifier & ReplaceStr(fld.Value, sTextQualifier, sTextQualifier & sTextQualifier) & sTextQualifier) & sFieldDelimiter
Else
strRecord = strRecord & CStr(Nz(sTextQualifier + fld.Value + sTextQualifier, vbNullString)) & sFieldDelimiter
End If
Else 'make sure there are no field delimiters in text fields
strRecord = strRecord & ReplaceStr(Nz(fld.Value, vbNullString), sFieldDelimiter, sReplaceWith) & sFieldDelimiter
End If
Case dbGUID 'exports canonical form
strRecord = strRecord & MidNzNz(fld.Value, vbNullString), 7, 38) & sFieldDelimiter
Case dbBinary, dbVarBinary, dbLongBinary
If Len(sTextQualifier) > 0 Then
If InStr(1, fld.Value, sTextQualifier, vbBinaryCompare) > 0 Then 'double text qualifiers
strRecord = strRecord & CStr(sTextQualifier & ReplaceStr(StrConv(fld.Value, vbUnicode), sTextQualifier, sTextQualifier & sTextQualifier) & sTextQualifier) & sFieldDelimiter
Else
strRecord = strRecord & CStr(Nz(sTextQualifier + StrConv(fld.Value, vbUnicode) + sTextQualifier, vbNullString)) & sFieldDelimiter
End If
Else 'make sure there are no field delimiters in text fields
strRecord = strRecord & ReplaceStr(Nz(StrConv(fld.Value, vbUnicode), vbNullString), sFieldDelimiter, sReplaceWith) & sFieldDelimiter
End If
Case Else
strRecord = strRecord & Nz(fld.Value, vbNullString) & sFieldDelimiter
End Select
Set fld = Nothing
End If
Next intCount
strRecord = ReplaceStr(strRecord, sRecDelimiter, sReplaceWith) 'make sure there's no record delimiters in records
strRecord = LeftstrRecordrd, Len(strRecord) - Len(sFieldDelimiter)) & sRecDelimiter
Put 'iFileNumber, , strRecord
lExportedCount = lExportedCount + 1
.MoveNext
Loop
End With

ExportRs = True

Exit_Here:
On Error Resume Next
Set fld = Nothing
Close iFileNumber
Call SysCmd(acSysCmdClearStatus)
Exit Function

Err_Handler:
Err.Raise Err.Number, Err.Source, Err.Description
Resume Exit_Here

End Function
Standard Export ExportSource Basic   66
Public Property Let ExportSource(varSource As Variant)
'required
'accepts a recordset, a tabledef, a querydef,
'a table name, a query name, a SQL statement
'or a 2-dim array
On Error GoTo 0
Dim strQueryName As String, strTableName As String
Dim qdf As DAO.QueryDef
Dim varElement As Variant

If IsObject(varSource) Then 'recordset or querydef or tabledef
If TypeOf varSource Is DAO.Recordset Then
If Not varSource Is Nothing Then Set oExport = varSource.Clone 'work with a copy
ElseIf TypeOf varSource Is DAO.TableDef Or TypeOf varSource Is DAO.QueryDef Then
Call SysCmd(acSysCmdSetStatus, "Opening source...")
Set oExport = varSource.OpenRecordset(dbOpenSnapshot)
Call SysCmd(acSysCmdClearStatus)
Else
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::ExportSource", "Invalid export source."
End If
ElseIf TypeNamevarSourcece) = "String" Then 'table name or query name or SQL
If odbCurrent Is Nothing Then _
Err.Raise ERR_EXP_DB_NOT_SPECIFIED, "ExportText::ExportSource", "Database not specified."
'try to use as SQL
If Not oExport Is Nothing Then oExport.Close: Set oExport = Nothing
Call SysCmd(acSysCmdSetStatus, "Opening source...")
On Error Resume Next
Set oExport = odbCurrent.OpenRecordset(CStr(varSource), dbOpenSnapshot)
On Error GoTo 0
Call SysCmd(acSysCmdClearStatus)
If oExport Is Nothing Then 'try as table name or query name
On Error Resume Next
strQueryName = odbCurrent.QueryDefs(CStr(varSource)).Name
If Not Len(strQueryName) > 0 Then _
strTableName = odbCurrent.TableDefs(CStr(varSource)).Name
On Error GoTo 0
If Len(strQueryName) > 0 Then
If Not (odbCurrent.QueryDefs(strQueryName).Type = dbQSelect Or odbCurrent.QueryDefs(strQueryName).Type = dbQSetOperation) Then _
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::ExportSource", "Invalid export source."
'query has to be either Select or Union
Call SysCmd(acSysCmdSetStatus, "Opening source...")
Set oExport = odbCurrent.OpenRecordset(strQueryName, dbOpenSnapshot)
Call SysCmd(acSysCmdClearStatus)
ElseIf Len(strTableName) > 0 Then
Call SysCmd(acSysCmdSetStatus, "Opening source...")
Set oExport = odbCurrent.OpenRecordset(strTableName, dbOpenSnapshot)
Call SysCmd(acSysCmdClearStatus)
Else
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::ExportSource", "Invalid export source."
End If
End If
ElseIf VarType(varSource) >= vbArray Then 'array
If Not ArrBoundsCheck(varSource) Then _
Err.Raise ERR_INVALID_EXPORT_ARRAY, "TextExport::ExportSource", "Invalid export array."
'make sure it's not an array of objects or array of arrays
'or something similarly unexportable
For Each varElement In varSource
If Not VarTypeCheck(varElement) Then _
Err.Raise ERR_INVALID_EXPORT_ARRAY, "TextExport::ExportSource", "Invalid export array."
Next varElement
vExport = varSource
Else
Err.Raise ERR_INVALID_EXPORT_SOURCE, "TextExport::ExportSource", "Invalid export source."
End If

End Property
Standard Export ExportType Basic   4
Public Property Let ExportType(strExportType As String)
'optional, "ASCII" (default) or "WP"
sExportType = strExportType
End Property
Standard Export FieldDelimiter Basic   4
Public Property Let FieldDelimiter(strFieldDelimiter As String)
'optional, Tab is default
sFieldDelimiter = strFieldDelimiter
End Property
Standard Export IncludeFieldNames Basic   5
Public Property Let IncludeFieldNames(blnIncludeFieldNames As Boolean)
'optional, Include is default
'ignored for arrays
bIncludeFieldNames = blnIncludeFieldNames
End Property
Standard Export NoProgressBar Basic   4
Public Property Let NoProgressBar(blnNoProgress As Boolean)
'if used, has to assigned before some other props
bNoProgress = blnNoProgress
End Property
Standard Export Nz Basic ExportRs (Procedure)
ExportArr (Procedure)
16
Private Function Nz(varIn, varValueIfNull) As Variant
'overloads Access Nz() function
'unlike Access, second argument is non-optional

'If Access Then
''Nz = Access.Nz(varIn, varValueIfNull)
'Else
Select Case True
Case IsNull(varIn), IsEmpty(varIn)
Nz = varValueIfNull
Case Else
Nz = varIn
End Select
'End If

End Function
Standard Export RecDelimiter Basic   4
Public Property Let RecDelimiter(strRecDelimiter As String)
'optional, CrLf is default
sRecDelimiter = strRecDelimiter
End Property
Standard Export RecordCount Basic   4
Public Property Get RecordCount() As Long
'number of actually exported records
RecordCount = lExportedCount
End Property
Standard Export ReplaceStr Basic ExportRs (Procedure)
ExportArr (Procedure)
79
Private Function ReplaceStr(strIn As String, strFind As String, strReplace As String) As String
Dim alngMap() As Long
Dim lngPos As Long
Dim lngCount As Long
Dim lngReplacementsCount As Long
Dim lngFindLength As Long
Dim lngReplaceLength As Long
Dim strTemp As String
Dim lngTempLength As Long

ReplaceStr = strIn

If LenB(ReplaceStr) <> 0 And LenB(strFind) <> 0 And StrComp(strFind, strReplace, vbBinaryCompare) <> 0 Then
lngReplacementsCount = 0
'map the replacements in the old string
lngPos = InStr(1, ReplaceStr, strFind, vbBinaryCompare)
If lngPos <> 0 Then
ReDim alngMap(0 To 1, 0 To Len(ReplaceStr) - 1) 'max required size
'alngMap(0, ) - old map before replacements
'alngMap(1, ) - new map after replacements
alngMap(0, 0) = lngPos
lngReplacementsCount = 1
Else
Exit Function
End If
lngFindLength = Len(strFind)
Do
lngPos = InStr(lngPos + lngFindLength, ReplaceStr, strFind, vbBinaryCompare)
If lngPos <> 0 Then
alngMap(0, lngReplacementsCount) = lngPos
lngReplacementsCount = lngReplacementsCount + 1
End If
Loop While lngPos <> 0

If lngReplacementsCount <> 0 Then 'at least one replacement
lngReplaceLength = Len(strReplace)
If lngFindLength <> lngReplaceLength Then
'calculate new string length after replacements
'and allocate temp string accordingly
lngTempLength = Len(ReplaceStr) + lngReplacementsCount * (lngReplaceLength - lngFindLength)
strTemp = SpacelngTempLengthth)
If lngTempLength <> 0 Then
'create new string mapping after replacements
For lngCount = 0 To lngReplacementsCount - 1
alngMap(1, lngCount) = alngMap(0, lngCount) + (lngReplaceLength - lngFindLength) * lngCount
Next lngCount
'replace
For lngCount = 0 To lngReplacementsCount
Select Case lngCount
Case 0 'string before first replacement position
'insert a piece of the original string before first replacement
MidstrTempmp, 1, alngMap(0, lngCount) - 1) = ReplaceStr
'insert the first replacement at the new mapped position
If alngMap(1, lngCount) < lngTempLength + 1 Then _
MidstrTempmp, alngMap(1, lngCount)) = strReplace
Case lngReplacementsCount 'string after last replacement position
'insert a piece of the original string, if any, after last replacement
If alngMap(1, lngCount - 1) + lngReplaceLength < lngTempLength + 1 Then _
MidstrTempmp, alngMap(1, lngCount - 1) + lngReplaceLength) = MidReplaceStrtr, alngMap(0, lngCount - 1) + lngFindLength)
Case Else 'string after previous and before next replacement
'insert a piece of the original string before next replacement
If alngMap(1, lngCount - 1) + lngReplaceLength < lngTempLength + 1 Then _
MidstrTempmp, alngMap(1, lngCount - 1) + lngReplaceLength) = MidReplaceStrtr, alngMap(0, lngCount - 1) + lngFindLength, alngMap(0, lngCount) - (alngMap(0, lngCount - 1) + lngFindLength))
'insert the next replacement at the new mapped position
If alngMap(1, lngCount) < lngTempLength + 1 Then _
MidstrTempmp, alngMap(1, lngCount)) = strReplace
End Select
Next lngCount
End If
ReplaceStr = strTemp
Else 'simple substitution
For lngCount = 0 To lngReplacementsCount - 1
MidReplaceStrtr, alngMap(0, lngCount)) = strReplace
Next lngCount
End If
End If
End If

End Function
Standard Export ReplaceWith Basic   7
Public Property Let ReplaceWith(strReplaceWith As String)
'optional
'strReplaceWith - will be used to replace sRecDelimiter
'and sFieldDelimiter (if no text qualifier is used) in the exported data
'default is to replace with one space
sReplaceWith = strReplaceWith
End Property
Standard Export SysCmd Basic ExportRs (Procedure)
ExportArr (Procedure)
ExportSource (Procedure)
Class_Terminate (Procedure)
32
Private Function SysCmd(Arg1 As Variant, Optional Arg2 As Variant, Optional Arg3 As Variant)
'overloads Access.SysCmd() within this module

If Not bNoProgress Then
'If Not VBA5 Then 'use events
If IsMissing(Arg2) And IsMissing(Arg3) Then 'clear status and progress
RaiseEvent StatusText(vbNullString)
RaiseEvent ExportProgress(0)
ElseIf Not IsMissing(Arg2) And IsMissing(Arg3) Then
Select Case Arg1
Case acSysCmdUpdateMeter
RaiseEvent ExportProgress(CSng(Arg2))
Case acSysCmdSetStatus
RaiseEvent StatusText(CStr(Arg2))
End Select
ElseIf Not IsMissing(Arg2) And Not IsMissing(Arg3) Then 'init progress
RaiseEvent StatusText(CStr(Arg2))
RaiseEvent ExportProgress(0)
End If
'ElseIf VBA5 And Access Then 'use Access SysCmd()
If IsMissing(Arg2) And IsMissing(Arg3) Then
''SysCmd = Access.SysCmd(Arg1)
ElseIf Not IsMissing(Arg2) And IsMissing(Arg3) Then
''SysCmd = Access.SysCmd(Arg1, Arg2)
ElseIf Not IsMissing(Arg2) And Not IsMissing(Arg3) Then
''SysCmd = Access.SysCmd(Arg1, Arg2, Arg3)
End If
'Else 'no status/progress reported
'End If
End If

End Function
Standard Export TextQualifier Basic   4
Public Property Let TextQualifier(strTextQualifier As String)
'optional, " is default
sTextQualifier = strTextQualifier
End Property
Standard Export VarTypeCheck Basic ExportSource (Procedure) 22
Private Function VarTypeCheck(varCheck As Variant) As Boolean
'Returns True if varCheck is an array element exportable as text
On Error GoTo 0
Dim intType As Integer

intType = VarType(varCheck)

If intType = vbEmpty Or _
intType = vbNull Or _
intType = vbInteger Or _
intType = vbLong Or _
intType = vbSingle Or _
intType = vbDouble Or _
intType = vbCurrency Or _
intType = vbDate Or _
intType = vbString Or _
intType = vbBoolean Or _
intType = vbDecimal Or _
intType = vbByte Then _
VarTypeCheck = True

End Function
Standard FastSearch CaptureChar Basic Products_FastSearch|FastList (Control) 54
Sub CaptureChar(poEvent As Object)

Dim oEvent As Object, ocList As Object, sTag As String, i As Integer
Dim vList() As Variant, vNewList() As Variant, iNew As Integer
Set oEvent = Events(poEvent)
If oEvent.EventType <> "KEYEVENT" Then Exit Sub

'Accepted keys: A-Z, a-z, BACKSPACE, ESCAPE. All other keys ignored
'Tag property of list box is used to keep sequence of entered characters
With oEvent
Set ocList = oEvent.Source
Select Case True
Case .KeyAlt, .KeyCtrl : Exit Sub
Case .KeyCode = com.sun.star.awt.Key.ESCAPE
ocList.Tag = ""
Call InitList()
Exit Sub
Case .KeyCode = com.sun.star.awt.Key.BACKSPACE
If Len(ocList.Tag) > 0 Then
sTag = ocList.Tag
ocList.Tag = Left(sTag, Len(sTag) - 1) ' Reduce length of Tag
Call InitList()
End If
Case (UCase(.KeyChar) >= "A" And UCase(.KeyChar) <= "Z") Or (.KeyCode = com.sun.star.awt.Key.SPACE)
ocList.Tag = ocList.Tag & .KeyChar
Case Else : Exit Sub
End Select
End With

With ocList ' Process Tag
sTag = .Tag
vList() = Split(.RowSource, ";")
.RowSource = ""
vNewList() = Array() ' Otherwise Redim protests
If UBound(vList) >= 0 Then
ReDim vNewList(0 To UBound(vList)) ' Resized later
iNew = 0 ' Counts valid entries in vList
For i = 0 To UBound(vList)
If Len(vList(i)) >= Len(sTag) Then
If UCase(Left(vList(i), Len(sTag))) = UCase(sTag) Then ' Case not sensitive
vNewList(iNew) = vList(i)
iNew = iNew + 1
End If
End If
Next i
If iNew > 0 Then
ReDim Preserve vNewList(0 To iNew - 1)
.RowSource = Join(vNewlist, ";") 'Apply new list after Tag selection
.ListIndex = 0 'Select first element
End If
End If
End With

End Sub
Standard FastSearch InitList Basic Products_FastSearch (Form)
CaptureChar (Procedure)
18
Sub InitList(Optional poEvent As Object)	'	Optional because also called from CaptureChar routine
'Activated when form opened and when ESC key is pressed in listbox

Const cstForm = "Products_FastSearch"
Const cstList = "FastList"
Dim ocList As Object, sSource As String

Set ocList = Forms(cstForm).Controls(cstList)
If Not IsMissing(poEvent) Then ocList.Tag = "" ' Initialized only when form opened

ocList.RowSourceType = com.sun.star.form.ListSourceType.SQL
ocList.RowSource = "SELECT [ProductName] FROM [Products] ORDER BY [ProductName] ASC" 'Requery implicit

sSource = Join(ocList.ItemData, ";")
ocList.RowSourceType = com.sun.star.form.ListSourceType.VALUELIST ' For performance
ocList.RowSource = sSource

End Sub
Standard FastSelect InitFirstList Basic Products_FastSelect (Form) 10
Sub InitFirstList(poEvent As Object)
'Activated when form opened

Dim ocList As Object, sSource As String

Set ocList = Forms(cstForm).Controls(cstLeftList)
sSource = Join(ocList.ItemData, ";")
ocList.RowSourceType = com.sun.star.form.ListSourceType.VALUELIST ' Cancel link with bound field
ocList.RowSource = sSource
End Sub
Standard FastSelect MoveItems Basic Products_FastSelect|MoveAllLeft (Control)
Products_FastSelect|MoveOneLeft (Control)
Products_FastSelect|MoveAllRight (Control)
Products_FastSelect|MoveOneRight (Control)
69
Sub MoveItems(poEvent As Object)
Dim oEvent As Object, ocLeftList As Object, ocRightList As Object
Dim i As Integer, vLeft() As Variant, vRight() As Variant, vSelected() As Variant
Dim iMaxDim As Integer, iLeftSize As Integer, iRightSize As Integer, sSource As String
Set oEvent = Events(poEvent)
Set ocLeftList = Forms(cstForm).Controls(cstLeftList)
Set ocRightList = Forms(cstForm).Controls(cstRightList)
' Initial load of arrays
vLeft = ocLeftList.ItemData
vRight = ocRightList.ItemData
iLeftSize = UBound(vLeft)
iRightSize = UBound(vRight)
iMaxDim = iLeftSize + 1 + iRightSize + 1
ReDim Preserve vLeft(iMaxDim)
ReDim Preserve vRight(iMaxDim)

Select Case oEvent.Source.Name
Case "MoveOneRight" ' >
vSelected = ocLeftList.Selected
For i = 0 To iLeftSize
If vSelected(i) Then
iRightSize = iRightSize + 1
vRight(iRightSize) = vLeft(i)
vLeft(i) = ""
End If
Next i
Case "MoveAllRight" ' >>
For i = 0 To iLeftSize
iRightSize = iRightSize + 1
vRight(iRightSize) = vLeft(i)
vLeft(i) = ""
Next i
Case "MoveOneLeft" ' <
vSelected = ocRightList.Selected
For i = 0 To iRightSize
If vSelected(i) Then
iLeftSize = iLeftSize + 1
vLeft(iLeftSize) = vRight(i)
vRight(i) = ""
End If
Next i
Case "MoveAllLeft" ' <<
For i = 0 To iRightSize
iLeftSize = iLeftSize + 1
vLeft(iLeftSize) = vRight(i)
vRight(i) = ""
Next i
End Select

'Reload listboxes
sSource = ""
For i = 0 To iLeftSize
If vLeft(i) <> "" Then sSource = sSource & vLeft(i) & ";"
Next i
If Len(sSource) = 0 Then ocLeftList.RowSource = "" Else ocLeftList.RowSource = Left(sSource, Len(sSource) - 1) ' Remove last ";"
sSource = ""
For i = 0 To iRightSize
If vRight(i) <> "" Then sSource = sSource & vRight(i) & ";"
Next i
If Len(sSource) = 0 Then ocRightList.RowSource = "" Else ocRightList.RowSource = Left(sSource, Len(sSource) - 1)' Remove last ";"

'Deselect listboxes
For i = 0 To ocLeftList.ListCount - 1
setSelected(ocLeftList, False, i)
Next i
For i = 0 To ocRightList.ListCount - 1
setSelected(ocRightList, False, i)
Next i
End Sub
Standard FillAuto EmpFillAuto Basic Employees_FillAuto|fmtEmployeeID (Control) 27
Sub EmpFillAuto(poEvent As Object)

Dim oEvent As Object, oEmpID As Object, sCrit As String
Dim oParentForm As Object, oField As Object, vValue As Variant
Set oEvent = Events(poEvent)
oEmpID = oEvent.Source
sCrit = "[EmployeeID]=" & oEmpID.Value
Set oParentForm = oEmpID.Parent
With oParentForm
Set oField = .Controls("txtTitleOfCourtesy")
vValue = DLookup("[TitleOfCourtesy]", "[Employees]", sCrit)
If Not IsNull(vValue) Then oField.Value = vValue
Set oField = .Controls("txtFirstName")
vValue = DLookup("[FirstName]", "[Employees]", sCrit)
If Not IsNull(vValue) Then oField.Value = vValue
Set oField = .Controls("txtLastName")
vValue = DLookup("[LastName]", "[Employees]", sCrit)
If Not IsNull(vValue) Then oField.Value = vValue
Set oField = .Controls("txtAddress")
vValue = DLookup("[Address]", "[Employees]", sCrit)
If Not IsNull(vValue) Then oField.Value = vValue
Set oField = .Controls("txtCity")
vValue = DLookup("[City]", "[Employees]", sCrit)
If Not IsNull(vValue) Then oField.Value = vValue
End With

End Sub
Standard HowTo AddRecordToShippers Basic   17
Sub AddRecordToShippers()
Dim odbNorthwind As Object
Dim orsShippers As Object

Set odbNorthwind = Application.CurrentDb
Set orsShippers = odbNorthwind.OpenRecordset("Shippers")

With orsShippers
.AddNew
.Fields("CompanyName").Value = "Global Open Source Service"
'
' Set remaining fields.
'
.Update
.mClose()
End With
End Sub
Standard HowTo CreateRecordsetFromForm Basic   15
Sub CreateRecordsetFromForm
Dim odbNorthwind As Object
Dim ofOrders As Object
Dim orsOrders As Object

Set odbNorthwind = Application.CurrentDb
Set ofOrders = Application.OpenForm("Orders_Tabbed")
Set orsOrders = ofOrders.Recordset

' ...
orsOrders.MoveLast
MsgBox orsOrders.RecordCount

orsOrders.mClose()
End Sub
Standard HowTo CreateRecordsetFromQuery Basic   13
Sub CreateRecordsetFromQuery
Dim odbNorthwind As Object
Dim orsCustomers As Object

Set odbNorthwind = Application.CurrentDb
Set orsCustomers = odbNorthwind.OpenRecordset("Customers union All")

' ...
orsCustomers.MoveLast
MsgBox orsCustomers.RecordCount

orsCustomers.mClose()
End Sub
Standard HowTo CreateRecordsetFromTable Basic   13
Sub CreateRecordsetFromTable
Dim odbNorthwind As Object
Dim orsShippers As Object

Set odbNorthwind = Application.CurrentDb
Set orsShippers = odbNorthwind.OpenRecordset("Shippers")

' ...
orsShippers.MoveLast
MsgBox orsShippers.RecordCount

orsShippers.mClose()
End Sub
Standard HowTo DisplayPosition Basic   48
Sub DisplayPosition()

Dim odbNorthwind As Object
Dim orsEmployees As Object
Dim sMsg As String
Dim lCount As Long
Dim sSQL As String
Dim dPercent As Double

On Local Error GoTo ErrorHandler

Set odbNorthwind = Application.CurrentDb

sSQL = "SELECT * FROM Employees"
Set orsEmployees = odbNorthwind.OpenRecordset(sSQL, , , dbReadOnly)

With orsEmployees
If .EOF Then ' If no records, exit
Exit Sub
Else
sMsg = "Processing Employees table..."
DoCmd.SysCmd(acSysCmdInitMeter, sMsg, 100)
.MoveLast ' Determine number of records
lCount = .RecordCount
.MoveFirst
End If
Do Until .EOF
'
' Any processing ...
'
Wait 100 ' just to see what happens ...
dPercent = .AbsolutePosition / lCount
If dPercent <> 0 Then DoCmd.SysCmd(acSysCmdUpdateMeter, sMsg, Int(100*dPercent))
.MoveNext
Loop
End With
MsgBox "Processing ended"
DoCmd.SysCmd(acSysCmdRemoveMeter)

orsEmployees.mClose
Set orsEmployees = Nothing
Set odbNorthwind = Nothing

Exit Sub

ErrorHandler:
TraceError("ERROR", Err, "DisplayPosition", Erl)
End Sub
Standard HowTo ExtractDataTable1Field Basic   19
Sub ExtractDataTable1Field()
Dim odbNorthwind As Object
Dim orsOrders As Object
Dim dOrderDate As Date
Dim sShipAddress As String
Dim sShipCity As String

Set odbNorthwind = Application.CurrentDb
Set orsOrders = odbNorthwind.OpenRecordset("Orders")

With orsOrders
.MoveFirst
dOrderDate = .Fields("OrderDate").Value
sShipAddress = .Fields("ShipAddress").Value
sShipCity = .Fields("ShipCity").Value
.mClose()
End With

End Sub
Standard HowTo ExtractDataTableBulk Basic   33
Sub ExtractDataTableBulk()
Dim odbNorthwind As Object
Dim orsOrders As Object
Dim vRecords As Variant
Dim iNumRows As Integer
Dim iNumColumns As Integer
Dim iRow As Integer
Dim iColumn As Integer
Dim sSQL As String

On Local Error GoTo ErrorHandler

Set odbNorthwind = Application.CurrentDb
sSQL = "SELECT [OrderDate],[ShipAddress],[ShipCity] FROM Orders"
Set orsOrders = odbNorthwind.OpenRecordset(sSQL)

vRecords = orsOrders.GetRows(10)
iNumRows = UBound(vRecords, 1) + 1
iNumColumns = UBound(vRecords, 2) + 1

For iRow = 0 To inumRows - 1
For iColumn = 0 To iNumColumns - 1
DebugPrint vRecords(iRow, iColumn)
Next iColumn
Next iRow

orsOrders.mClose()
Set orsOrders = Nothing
Exit Sub

ErrorHandler:
TraceError("ERROR", Err, "ExtractDataTableBulk", Erl)
End Sub
Standard HowTo FindLimitsRecordset Basic   21
Sub FindLimitsRecordset()
Dim odbNorthwind As Object
Dim orsOrders As Object
Set odbNorthwind = Application.CurrentDb
Set orsOrders = odbNorthwind.OpenRecordset("Orders")

' Do until ending of file.
Do Until orsOrders.EOF
' Manipulate the data.
orsOrders.MoveNext ' Move to the next record.
Loop

orsOrders.MoveLast ' Move to the last record.
' Do until beginning of file.
Do Until orsOrders.BOF
' Manipulate the data.
orsOrders.MovePrevious ' Move to the previous record.
Loop

orsOrders.mClose()
End Sub
Standard HowTo FindRecordCount Basic Main (Procedure) 25
Function FindRecordCount(sSQL As String) As Long

Dim odbNorthwind As Object
Dim orsRecords As Object
On Local Error GoTo ErrorHandler

Set odbNorthwind = Application.CurrentDb
Set orsRecords = odbNorthwind.OpenRecordset(sSQL)
With orsRecords
If .EOF Then
FindRecordCount = 0
Else
.MoveLast
FindRecordCount = .RecordCount
End If
.mClose
End With

Set orsRecords = Nothing
Set odbNorthwind = Nothing
Exit Function

ErrorHandler:
TraceError("ERROR", Err, "FindRecordCount", Erl)
End Function
Standard HowTo Main Basic   3
Sub Main()
MsgBox FindRecordCount("Products")
End Sub
Standard Images ExportImages Basic   16
Sub ExportImages(psPath As String)

Dim oTable As Object, oRecordset As Object, sCatName As String
Set oTable = Application.CurrentDb().TableDefs("CATEGORIES")
Set oRecordset = oTable.OpenRecordset()

With oRecordset
Do While Not .EOF()
sCatName = Join(Split(.Fields("CATEGORYNAME").Value, "/"), " ")
.Fields("Picture").WriteAllBytes(psPath & sCatName & ".png")
.MoveNext
Loop
.mClose()
End With

End Sub
Standard Images ImportImages Basic   18
Sub ImportImages(psPath As String)

Dim oTable As Object, oRecordset As Object, sCatName As String
Set oTable = Application.CurrentDb().TableDefs("CATEGORIES")
Set oRecordset = oTable.OpenRecordset()

With oRecordset
Do While Not .EOF()
sCatName = Join(Split(.Fields("CATEGORYNAME").Value, "/"), " ")
.Edit
.Fields("Picture").ReadAllBytes(psPath & sCatName & ".png")
.Update
.MoveNext
Loop
.mClose()
End With

End Sub
Standard Images Main Basic   4
Sub Main
'ImportImages("Put/here/a/correct/pathname/")
'ExportImages("Put/here/a/correct/pathname/")
End Sub
Standard ListBox AddAllToList Basic Products_ListBoxFilter (Form) 22
Sub AddAllToList(poEvent As Object)

Dim oEvent As Object, ofForm As Object, ocList As Object
Dim i As Integer, sSource As String
Set oEvent = Events(poEvent)
Set ofForm = oEvent.Source
Set ocList = ofForm.Controls("listBox-All")
With ocList
Select Case .RowSourceType
Case com.sun.star.form.ListSourceType.VALUELIST
.RowSource = "(All);" & .RowSource
Case Else ' Table, Query, SQL, SqlPassThrough
sSource = "(All)"
For i = 0 To .ListCount - 1
sSource = sSource & ";" & .Itemdata(i)
Next i
.RowSourceType = com.sun.star.form.ListSourceType.VALUELIST
.RowSource = sSource
End Select
End With

End Sub
Standard ListBox SyncFormListBoxFilter Basic   14
Sub SyncFormListBoxFilter(poEvent As Object)

Dim oEvent As Object, ocList As Object, oForm As Object
Dim sSupplier As String, lSupplier As Long

Set oEvent = Events(poEvent)
Set ocList = oEvent.Source ' Retrieve listbox object
Set oForm = ocList.Parent ' Retrieve parent form
sSupplier = Join(Split(ocList.Value, "'"), "''") ' For the case the company name contains quotes
lSupplier = DLookup("[SupplierID]", "[Suppliers]", "[CompanyName]='" & sSupplier & "'")
oForm.Filter = "[SupplierID]=" & lSupplier
oForm.FilterOn = True

End Sub
Standard ListBox SyncFormListBoxMono Basic Products_ListBoxFilter|SuppliersListBoxMono (Control) 13
Sub SyncFormListBoxMono(poEvent As Object)

Dim oEvent As Object, ocList As Object, oForm As Object
Dim sSupplier As String, lSupplier As Long

Set oEvent = Events(poEvent)
Set ocList = oEvent.Source ' Retrieve listbox object
Set oForm = ocList.Parent ' Retrieve parent form
sSupplier = Join(Split(ocList.Value, "'"), "''") ' For the case the company name contains quotes
lSupplier = DLookup("[SupplierID]", "[Suppliers]", "[CompanyName]='" & sSupplier & "'")
oForm.RecordSource = "SELECT [SupplierID], [ProductID], [ProductName], [UnitPrice] FROM [Products] WHERE [SupplierID]=" & lSupplier

End Sub
Standard ListBox SyncFormListBoxMulti Basic Products_ListBoxFilter|SuppliersListBoxMulti (Control) 20
Sub SyncFormListBoxMulti(poEvent As Object)

Dim oEvent As Object, ocList As Object, oForm As Object
Dim sSupplier As String, lSupplier As Long, i As Integer, sSQL As String
Const cstCriteria = " OR [SupplierID]="

Set oEvent = Events(poEvent)
Set ocList = oEvent.Source ' Retrieve listbox object
Set oForm = ocList.Parent ' Retrieve parent form
sSQL = "SELECT [SupplierID], [ProductID], [ProductName], [UnitPrice] FROM [Products] WHERE [SupplierID]="
For i = 0 To UBound(oclist.Selected)
If ocList.Selected(i) Then
sSupplier = Join(Split(ocList.ItemData(i), "'"), "''") ' For the case the company name contains quotes
lSupplier = DLookup("[SupplierID]", "[Suppliers]", "[CompanyName]='" & sSupplier & "'")
sSQL = sSQL & lSupplier & cstCriteria
End If
Next i
oForm.RecordSource = Left(sSQL, Len(sSQL) - Len(cstCriteria)) ' Trim SQL phrase

End Sub
Standard NewRec AskBeforeSave Basic Customers_NewRec (Form) 21
Function AskBeforeSave(poEvent As Object) As Boolean

Dim sMsg As String, oEvent As Object

REM MsgBox constants
'Const vbYesNo = 4 ' Yes and No buttons
'Const vbQuestion = 32 ' Warning query
'Const vbYes = 6 ' Yes button pressed

AskBeforeSave = True
Set oEvent = Events(poEvent)
If oEvent.Recommendation = "IGNORE" Then Exit Function
If oEvent.RowChangeAction <> com.sun.star.sdb.RowChangeAction.UPDATE Then Exit Function ' INSERT / DELETE ignored
sMsg = "Data has changed." & Chr(13) & "Do you wish to save the changes?" _
& Chr(13) & "Click Yes to save or No to discard changes."
If MsgBox(sMsg, vbQuestion + vbYesNo, "Save record ?") <> vbYes Then
RunCommand("RecUndo") ' Cancel editing done
AskBeforeSave = False
End If

End Function
Standard NewRec SetDefaultNewRec Basic Customers_NewRec (Form) 8
Sub SetDefaultNewRec(poEvent As Object)

Dim ofForm As Object, ocControl As Object
Set ofForm = Events(poEvent).Source ' Get the current form
Set ocControl = ofForm.Controls("txtCountry")
ocControl.DefaultValue = ocControl.Value

End Sub
Standard OutputTo Main Basic   8
Sub Main
Dim sOutputFile As String, sTemplateFile As String, n As Integer
For n = 1 To 8
sOutputFile = "/home/jean-pierre/Documents/Access2Base/Doc/Access2Base/_outputto/output" & n & ".html"
sTemplateFile = "/home/jean-pierre/Documents/Access2Base/Doc/Access2Base/_outputto/template" & n & ".html"
DoCmd.OutputTo(acOutputQuery, "EmployeesList", acFormatHtml, sOutputFile, False, sTemplateFile, acUTF8Encoding)
Next n
End Sub
Standard Records DMedian Basic   37
Public Function DMedian( _
psField As String _
, psTable As String _
, Optional psWhere As String _
) As Variant

Dim sSql As String, oRecordset As Object, vValue1 As variant, oField As Object
Const cstQuote = """"

DMedian = Null ' If no records ...

sSql = "SELECT " _
& cstQuote & psField & cstQuote _
& " FROM " & cstQuote & psTable & cstQuote _
& Iif(IsMissing(psWhere), "", " WHERE " & psWhere) _
& " ORDER BY " & cstQuote & psField & cstQuote
Set oRecordset = CurrentDb().OpenRecordset(sSql)

With oRecordset
.MoveLast() ' Necessary to know the exact number of records
If Not .EOF() Then ' At least 1 record ?
Select Case .RecordCount Mod 2
Case 0 ' Even
.AbsolutePosition = .RecordCount / 2
Set oField = .Fields(psField)
vValue1 = oField.Value
.MoveNext
DMedian = (.oField.Value + vValue1) / 2
Case 1 ' Odd
.AbsolutePosition = Int(.RecordCount / 2) + 1 ' Works also if only 1 record
DMedian = .Fields(psField).Value
End Select
End If
.mClose()
End With

End Function
Standard Records DPercentile Basic Main (Procedure) 34
Public Function DPercentile( _
pdPercentile As Double _
, psField As String _
, psTable As String _
, Optional psWhere As String _
) As Variant

Dim sSql As String, oRecordset As Object, vValue1 As variant, oField As Object
Const cstQuote = """"

DPercentile = Null
If pdPercentile < 0 Or pdPercentile > 1 Then Exit Function

sSql = "SELECT " _
& cstQuote & psField & cstQuote _
& " FROM " & cstQuote & psTable & cstQuote _
& Iif(IsMissing(psWhere), "", " WHERE " & psWhere) _
& " ORDER BY " & cstQuote & psField & cstQuote
Set oRecordset = CurrentDb().OpenRecordset(sSql)

With oRecordset
.MoveLast() ' Necessary to know the exact number of records
If pdPercentile < 1 Then
If Not .EOF() Then ' At least 1 record ?
.AbsolutePosition = Int(CDbl(.RecordCount * pdPercentile + 0.5) + 0.5)
DPercentile = .Fields(psField).Value
End If
Else ' If Percentile = 1 take highest value
DPercentile = .Fields(psField).Value
End If
.mClose()
End With

End Function
Standard Records Main Basic   4
Sub Main
'MsgBox DMedian("UnitPrice", "Products")
MsgBox DPercentile(0.25, "UnitPrice", "Products")
End Sub
Standard Snippets Example1 Basic Main (Procedure) 3
Sub Example1()
MsgBox CurrentDb.MetaData.IdentifierQuoteString
End Sub
Standard Snippets Example2 Basic   5
Sub Example2()	'	Form presumed open
Dim ofForm As Object
Set ofForm = Forms("Orders_Browse")
MsgBox getUNOTypeName(ofForm.DatabaseForm)
End Sub
Standard Snippets Example3 Basic   5
Sub Example3()	'	Form presumed open
Dim ocControl As Object
Set ocControl = Forms("Orders_Browse").Controls("txtCustomerID")
ocControl.ControlModel.FontStrikeout = com.sun.star.awt.FontStrikeout.DOUBLE
End Sub
Standard Snippets getUNOTypeName Basic Example2 (Procedure) 20
Public Function getUNOTypeName(pvObject As Variant) As String
' Return the symbolic name of the pvObject (UNO-object) type
' Code-snippet from XRAY

Dim oService As Object, vClass as Variant, sType As String
_getUNOTypeName = ""
On Local Error Resume Next
sType = pvObject.getImplementationName()
If sType = "" Then
oService = CreateUnoService("com.sun.star.reflection.CoreReflection")
vClass = oService.getType(pvObject)
If vClass.TypeClass = com.sun.star.uno.TypeClass.STRUCT Then
getUNOTypeName = vClass.Name
End If
oService.Dispose()
End If

getUNOTypeName = sType

End Function ' getUNOTypeName
Standard Snippets Main Basic   3
Sub Main
Example1()
End Sub
Standard Synchro SyncCloseForms Basic   15
Sub SyncCloseForms(poEvent As Object)

' Fired at each component closure !!

Dim oEvent As Object
'Const acForm = 2
Const cstMainForm = "Orders_Details_Sync_Cust-Prod-Emp"
Set oEvent = Events(poEvent)
If UCase(oEvent.SubComponentName) <> UCase(cstMainForm) Then Exit Sub
DoCmd.mClose acForm, "Customers_Sync_Orders"
DoCmd.mClose acForm, "Employees_Sync_Orders"
DoCmd.mClose acForm, "Products_Sync_Orders"
Exit Sub

End Sub
Standard Synchro SyncForms Basic Orders_Details_Sync_Cust-Prod-Emp (Form)
Orders_Details_Sync_Cust-Prod-Emp|btnCustomers (Control)
Orders_Details_Sync_Cust-Prod-Emp|btnEmployees (Control)
Orders_Details_Sync_Cust-Prod-Emp|btnProducts (Control)
Orders_Details_Sync_Cust-Prod-Emp|SubForm (Control)
46
Sub SyncForms(poEvent As Object)

Dim ofForm As Object, oeEvent As Object, oTrigger As Object, oMainForm As Object
Dim sFilter As String, sEmployee As String, sCustomer As String, sProduct As String
Dim i As Integer, sForm As String
Const cstMainForm = "Orders_Details_Sync_Cust-Prod-Emp"
Const cstSuffix = "_Sync_Orders" ' Suffix of auxiliary form names

Set oeEvent = Events(poEvent)
Set oTrigger = oeEvent.Source ' Determine the trigger: one of the buttons ? or record navigation in main form ?
' or record navigation in subform ?
Set oMainForm = AllForms(cstMainForm)
If Not oMainForm.IsLoaded Then Goto Exit_Sub ' May happen at form loading or closure

If Left(oTrigger.Name, Len("btn")) = "btn" Then ' Triggered by buttons btnCustomers, btnProducts or btnEmployees
sForm = Right(oTrigger.Name, Len(oTrigger.Name)- Len("btn")) & cstSuffix
Set ofForm = AllForms(sForm) ' AllForms() collects all forms, whether open or not
If ofForm.IsLoaded Then setFocus(ofForm) Else OpenForm(sForm)
End If

'Determine filters
sCustomer = "[CustomerID]='" & oMainForm.Controls("txtCustomerID").Value & "'" ' String !!!
sProduct = "[ProductID]=" & oMainForm.Controls("SubForm").Form.Controls("SubForm_Grid").Controls("ProductID").Value
sEmployee = "[EmployeeID]=" & oMainForm.Controls("fmtEmployeeID").Value
For i = 0 To Forms().Count - 1 ' Forms() collects all open forms
Set ofForm = Forms(i)
sFilter = ""
Select Case Split(ofForm.Name, cstSuffix)(0)
Case "Customers" : sFilter = sCustomer
Case "Products" : sFilter = sProduct
Case "Employees" : sFilter = sEmployee
Case Else ' Ignore any other open form
End Select
If Len(sFilter) > 0 Then
ofForm.Filter = sFilter
ofForm.FilterOn = True
End If
Next i

Exit_Sub:
Set ofForm = Nothing
Set oeEvent = Nothing
Set oTrigger =Nothing
Set oMainForm = Nothing
Exit Sub
End Sub
Standard Tabbed SelectTab Basic Orders_Tabbed|btnDetails (Control)
Orders_Tabbed|btnOrders (Control)
18
Public Sub SelectTab(Optional poEvent As Object)

Dim oEvent As Object, oForm As Object
Set oEvent = Application.Events(poEvent)
Set oForm = Forms("Orders_Tabbed")
If oEvent.Source.Name = "btnOrders" Then
oForm.Component.TextSections.getByIndex(1).IsVisible = False
oForm.Component.TextSections.getByIndex(0).IsVisible = True
oEvent.Source.Value = True
oForm.Controls("btnDetails").Value = False
Else ' btnDetails
oForm.Component.TextSections.getByIndex(0).IsVisible = False
oForm.Component.TextSections.getByIndex(1).IsVisible = True
oEvent.Source.Value = True
oForm.Controls("btnOrders").Value = False
End If

End Sub
Standard Test Main Basic   6
Sub Main
Dim a
Set a = Forms("Products_ListboxFilter").Controls("SuppliersListBoxMono")
XRay a.ControlModel
MsgBox Utils._hasUNOProperty(a.ControlModel, "StringItemList")
End Sub
Standard Test TestGetTable Basic   6
Sub TestGetTable()
Dim oRs As Object, vData As Variant
Set oRs = Application.CurrentDb.OpenRecordset("Employees")
vData = oRs.GetRows(50, True)
oRs.mClose
End Sub
Standard Tiptext setTipText Basic Orders_Browse (Form) 19
Sub setTipText(poEvent As Object)

Dim ofForm As Object, ocControl As Object, i As Integer, sValue As String
Const cstMin = 10
Const cstMax = 200
Set ofForm = Events(poEvent).Source
For i = 0 To ofForm.Controls.Count - 1
Set ocControl = ofForm.Controls(i)
sValue = CStr(ocControl.Value)
If Len(sValue) > cstMin Then
If Len(sValue) > cstMax Then
ocControl.ControlTiptext = Left(sValue, cstMax)
Else
ocControl.ControlTiptext = sValue
End If
End If
Next i

End Sub
Standard Zoom ZoomInit Basic Products_ZoomImage (Form) 6
Sub ZoomInit(poEvent As Object)
Dim ofForm As Object, ocZoom As Object
Set ofForm = Events(poEvent).Source
Set ocZoom = ofForm.Controls("imgZoom")
ocZoom.Visible = False
End Sub
Standard Zoom ZoomInOut Basic Products_ZoomImage|imgPicture (Control) 6
Sub ZoomInOut(poEvent As Object)
Dim ofForm As Object, ocZoom As Object
Set ofForm = Events(poEvent).Source.Parent
Set ocZoom = ofForm.Controls("imgZoom")
ocZoom.Visible = Not ocZoom.Visible
End Sub