user-defined mixed listing query in sql - sql

suppose that,
I have a db which is included USR_NR field (integer type). and I know all datas in field. no any surprises nr.
USR_NR : 1,3,4,7,9,12,44,13,78
I need to listed this field as mixed like 1,78,44,9,7,3,12,4,13
there is no rule for listing. I want to sort the way I wanted.
I tried with ORDER BY but how can I advance ?
I can not use ASC , DESC
SELECT * FROM DB ORDER BY ?
could you help me for this ?

What you need is a form where you can set a priority number for each record using a function like this:
' Set the priority order of a record relative to the other records of a form.
'
' The table/query bound to the form must have an updatable numeric field for
' storing the priority of the record. Default value of this should be Null.
'
' Requires:
' A numeric, primary key, typical an AutoNumber field.
'
' 2018-08-31. Gustav Brock, Cactus Data ApS, CPH.
'
Public Sub RowPriority( _
ByRef TextBox As Access.TextBox, _
Optional ByVal IdControlName As String = "Id")
' Error codes.
' This action is not supported in transactions.
Const NotSupported As Long = 3246
Dim Form As Access.Form
Dim Records As DAO.Recordset
Dim RecordId As Long
Dim NewPriority As Long
Dim PriorityFix As Long
Dim FieldName As String
Dim IdFieldName As String
Dim Prompt As String
Dim Buttons As VbMsgBoxStyle
Dim Title As String
On Error GoTo Err_RowPriority
Set Form = TextBox.Parent
If Form.NewRecord Then
' Will happen if the last record of the form is deleted.
Exit Sub
Else
' Save record.
Form.Dirty = False
End If
' Priority control can have any Name.
FieldName = TextBox.ControlSource
' Id (primary key) control can have any name.
IdFieldName = Form.Controls(IdControlName).ControlSource
' Prepare form.
DoCmd.Hourglass True
Form.Repaint
Form.Painting = False
' Current Id and priority.
RecordId = Form.Controls(IdControlName).Value
PriorityFix = Nz(TextBox.Value, 0)
If PriorityFix <= 0 Then
PriorityFix = 1
TextBox.Value = PriorityFix
Form.Dirty = False
End If
' Disable a filter.
' If a filter is applied, only the filtered records
' will be reordered, and duplicates might be created.
Form.FilterOn = False
' Rebuild priority list.
Set Records = Form.RecordsetClone
Records.MoveFirst
While Not Records.EOF
If Records.Fields(IdFieldName).Value <> RecordId Then
NewPriority = NewPriority + 1
If NewPriority = PriorityFix Then
' Move this record to next lower priority.
NewPriority = NewPriority + 1
End If
If Nz(Records.Fields(FieldName).Value, 0) = NewPriority Then
' Priority hasn't changed for this record.
Else
' Assign new priority.
Records.Edit
Records.Fields(FieldName).Value = NewPriority
Records.Update
End If
End If
Records.MoveNext
Wend
' Reorder form and relocate record position.
' Will fail if more than one record is pasted in.
Form.Requery
Set Records = Form.RecordsetClone
Records.FindFirst "[" & IdFieldName & "] = " & RecordId & ""
Form.Bookmark = Records.Bookmark
PreExit_RowPriority:
' Enable a filter.
Form.FilterOn = True
' Present form.
Form.Painting = True
DoCmd.Hourglass False
Set Records = Nothing
Set Form = Nothing
Exit_RowPriority:
Exit Sub
Err_RowPriority:
Select Case Err.Number
Case NotSupported
' Will happen if more than one record is pasted in.
Resume PreExit_RowPriority
Case Else
' Unexpected error.
Prompt = "Error " & Err.Number & ": " & Err.Description
Buttons = vbCritical + vbOKOnly
Title = Form.Name
MsgBox Prompt, Buttons, Title
' Restore form.
Form.Painting = True
DoCmd.Hourglass False
Resume Exit_RowPriority
End Select
End Sub
It is explained in detail in my article which includes a demo as well:
Sequential Rows in Microsoft Access
If you don't have an account, browse for the link: Read the full article.
Code is also on GitHub: VBA.RowNumbers

You can use instr():
order by instr(",1,78,44,9,7,3,12,4,13,", "," & USR_NR & ",")
Or, somewhat more verbosely, use switch:
order by switch(USR_NR = 1, 1,
USR_NR = 78, 2,
USR_NR = 44, 3,
. . .
)

Related

How do I assign an already known integer to a field after the NotInList event is called?

I have this complicated VBA function on a MSAccess form frm_DataEntry. It searches for values which are not in a list. The function is called on de NotInList event of the comboboxes.
When the typed string in combobox cbo_CustomerLocations is not in the list, it will ask if I want to add it to the table tbl_CustomerLocations by Yes/No question. After that it goes from 1st column to the last column and asks if I want to add some new data. The code below shows how to add a CustomerLocation.
The last field CustomerID of my table tbl_CustomerLocations is linked to the CustomerID field of table tbl_Customers
Now my question:
How do I alter my VBA code when the NotInList event is called, and when it reaches the CustomerID column (the last column), It must not ask 'What do you want for CustomerID', but rather automatically selects the CustomerID I previously selected on the same form frm_DataEntry on combobox cbo_Customers?
Private Sub cbo_CustomerLocationID_NotInList(NewData As String, Response As Integer)
Dim oRS As DAO.Recordset, i As Integer, sMsg As String
Dim oRSClone As DAO.Recordset
Response = acDataErrContinue
String_Value = Me.cbo_CustomerLocationID.Text
MsgBold = String_Value
MsgNormal = "Add to list with locations?"
Debug.Print
If Eval("MsgBox ('" & MsgBold & vbNewLine _
& "#" & MsgNormal & "##', " & vbYesNo & ", 'New Location')") = vbYes Then
Set oRS = CurrentDb.OpenRecordset("tbl_CustomerLocations", dbOpenDynaset)
oRS.AddNew
oRS.Fields(1) = NewData
For i = 2 To oRS.Fields.Count - 1
sMsg = "What do you want for " & oRS(i).Name
oRS(i).Value = InputBox(sMsg, , oRS(i).DefaultValue)
Next i
oRS.Update
cbo_CustomerLocationID = Null
cbo_CustomerLocationID.Requery
DoCmd.OpenTable "tbl_CustomerLocations", acViewNormal, acReadOnly
Me.cbo_CustomerLocationID.Text = String_Value
End If
End Sub
Use an If Then block within the loop to check for name of field.
If oRS(i).Name = "CustomerID" Then
oRS(i) = Me.cbo_Customers
Else
sMsg = "What do you want for " & oRS(i).Name
oRS(i).Value = InputBox(sMsg, , oRS(i).DefaultValue)
End If

combo box to select value w/ multiple duplicates & populating textbox in form w/ value from each duplicate record, line by line?

I'm currently trying to do as said in the title, but cannot find a reliable and working vba code to use.
The database contains 2 forms and 2 tables.
1 table needs 1 unique record per name with multiple 'description values', while the other has multiple duplicate records per name with only 1 'description value' each.
The 'unique name' table needs to have a single record containing all the 'description values' from the 'duplicate name' table's multiple records' 'description value'.
I was under the impression that using a DLookup querying the 'duplicate names' on the 'duplicate name's table would return all the 'description values' that i could just set to the textbox's value i.e.
Me.txtDescription.Value = DLookup("[Description]", "Duplicates Table", "[Dupe Names] = '" & cboUniqueName & "'")
But it would only return a single record into the text box. I've also tried the following code
Dim dQry As String
Dim dupeItems
Dim dupeList() As String
dQry = Me.cboUniqueName.Value
dupeItems = DLookup("Description", "Duplicates Table", "[Dupe Names] = '" & dQry & "'")
i = 0
For Each dupeItem In dupeItems
ReDim Preserve dupeList(i)
dupeList(i) = dupeItem
i = i + 1
Next
Me.txtDescription.Value = dupeList
But this didn't work either.
Is there a known method of doing so? - I'm not very experienced with vba, so maybe I overlooked the answer to my problems.
I can try to rephrase my question if need be, but this is what I could think of.
Thank you!
You can use my generic DJoin function for this having a line feed as the separator:
Dim dQry As String
Dim dupeItems As String
dQry = Me.cboUniqueName.Value
dupeItems = DJoin("Description", "[Duplicates Table]", "[Dupe Names] = '" & dQry & "'", vbCrLf)
Me.txtDescription.Value = dupeItems
The function (complete module):
Option Explicit
' Returns the joined (concatenated) values from a field of records having the same key.
' The joined values are stored in a collection which speeds up browsing a query or form
' as all joined values will be retrieved once only from the table or query.
' Null values and zero-length strings are ignored.
'
' If no values are found, Null is returned.
'
' The default separator of the joined values is a space.
' Optionally, any other separator can be specified.
'
' Syntax is held close to that of the native domain functions, DLookup, DCount, etc.
'
' Typical usage in a select query using a table (or query) as source:
'
' Select
' KeyField,
' DJoin("[ValueField]", "[Table]", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' The source can also be an SQL Select string:
'
' Select
' KeyField,
' DJoin("[ValueField]", "Select ValueField From SomeTable Order By SomeField", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' To clear the collection (cache), call DJoin with no arguments:
'
' DJoin
'
' Requires:
' CollectValues
'
' 2019-06-11, Cactus Data ApS, Gustav Brock
'
Public Function DJoin( _
Optional ByVal Expression As String, _
Optional ByVal Domain As String, _
Optional ByVal Criteria As String, _
Optional ByVal Delimiter As String = " ") _
As Variant
' Expected error codes to accept.
Const CannotAddKey As Long = 457
Const CannotReadKey As Long = 5
' SQL.
Const SqlMask As String = "Select {0} From {1} {2}"
Const SqlLead As String = "Select "
Const SubMask As String = "({0}) As T"
Const FilterMask As String = "Where {0}"
Static Values As New Collection
Dim Records As DAO.Recordset
Dim SubRecords As DAO.Recordset
Dim Sql As String
Dim SqlSub As String
Dim Filter As String
Dim Value As Variant
Dim Result As Variant
On Error GoTo Err_DJoin
If Expression = "" Then
' Erase the collection of keys.
Set Values = Nothing
Result = Null
Else
' Get the values.
' This will fail if the current criteria hasn't been added
' leaving Result empty.
Result = Values.Item(Criteria)
'
If IsEmpty(Result) Then
' The current criteria hasn't been added to the collection.
' Build SQL to lookup values.
If InStr(1, LTrim(Domain), SqlLead, vbTextCompare) = 1 Then
' Domain is an SQL expression.
SqlSub = Replace(SubMask, "{0}", Domain)
Else
' Domain is a table or query name.
SqlSub = Domain
End If
If Trim(Criteria) <> "" Then
' Build Where clause.
Filter = Replace(FilterMask, "{0}", Criteria)
End If
' Build final SQL.
Sql = Replace(Replace(Replace(SqlMask, "{0}", Expression), "{1}", SqlSub), "{2}", Filter)
' Look up the values to join.
Set Records = CurrentDb.OpenRecordset(Sql, dbOpenSnapshot)
CollectValues Records, Delimiter, Result
' Add the key and its joined values to the collection.
Values.Add Result, Criteria
End If
End If
' Return the joined values (or Null if none was found).
DJoin = Result
Exit_DJoin:
Exit Function
Err_DJoin:
Select Case Err
Case CannotAddKey
' Key is present, thus cannot be added again.
Resume Next
Case CannotReadKey
' Key is not present, thus cannot be read.
Resume Next
Case Else
' Some other error. Ignore.
Resume Exit_DJoin
End Select
End Function
' To be called from DJoin.
'
' Joins the content of the first field of a recordset to one string
' with a space as delimiter or an optional delimiter, returned by
' reference in parameter Result.
'
' 2019-06-11, Cactus Data ApS, Gustav Brock
'
Private Sub CollectValues( _
ByRef Records As DAO.Recordset, _
ByVal Delimiter As String, _
ByRef Result As Variant)
Dim SubRecords As DAO.Recordset
Dim Value As Variant
If Records.RecordCount > 0 Then
While Not Records.EOF
Value = Records.Fields(0).Value
If Records.Fields(0).IsComplex Then
' Multi-value field (or attachment field).
Set SubRecords = Records.Fields(0).Value
CollectValues SubRecords, Delimiter, Result
ElseIf Nz(Value) = "" Then
' Ignore Null values and zero-length strings.
ElseIf IsEmpty(Result) Then
' First value found.
Result = Value
Else
' Join subsequent values.
Result = Result & Delimiter & Value
End If
Records.MoveNext
Wend
Else
' No records found with the current criteria.
Result = Null
End If
Records.Close
End Sub
Full documentation and demo can be found here:
Join (concat) values from one field from a table or query

Concatenating multiple rows, with multiple values in it, into single line in MS Access

I am trying to create simple requirements management database. Basically I have 2 tables like below:
Contract_requirements with 2 columns:
CR_ReqID | Description
reqCR1 | Contract req description 1
reqCR2 | Contract req description 2
SW_requirements
Title | SW_ReqID | RootReq
SW req description 1| reqSW1 | reqCR1, reqCR2
SW req description 2| reqSW2 | reqCR1
SW req description 3| reqSW3 | reqCR2
And I would like to write query to receive such a table:
CR_ReqID |Description |where used?
reqCR1 |Contract req description 1 |reqSW1, reqSW2
reqCR2 |Contract req description 2 |reqSW1, reqSW3
Tables "Contract requirements" and "SW requirements" are in relation via column "RootReq"
Ive tried to implement code from Allen Browne
http://allenbrowne.com/func-concat.html#Top
This is my query
SELECT Contract_requirements.CR_ReqID, ConcatRelated("SW_ReqID ","SW_requirements","RootReq = """ & [CR_ReqID] & """") AS Expr1
FROM Contract_requirements;
but I get error in Access
"Error3831: The multi-valued field 'RootReq' cannot be used in a WHERE or HAVING clause"
Could you guys help me to make this working?
Thanks in advance
Build a query that expands the multi-value field elements to individual records.
Query1
SELECT SW_Requirements.Title, SW_Requirements.SW_ReqID, SW_Requirements.RootReq.Value
FROM SW_Requirements;
Then use that query as source for ConcatRelated() function.
SELECT Contract_Requirements.*,
ConcatRelated("SW_ReqID","Query1","[SW_Requirements.RootReq.Value]='" & [CR_ReqID] & "'") AS WhereUsed
FROM Contract_Requirements;
Advise not to use spaces nor punctuation/special characters in naming convention.
You can also use my DJoin function as this will accept SQL as the source, thus you won't need additional saved queries:
' Returns the joined (concatenated) values from a field of records having the same key.
' The joined values are stored in a collection which speeds up browsing a query or form
' as all joined values will be retrieved once only from the table or query.
' Null values and zero-length strings are ignored.
'
' If no values are found, Null is returned.
'
' The default separator of the joined values is a space.
' Optionally, any other separator can be specified.
'
' Syntax is held close to that of the native domain functions, DLookup, DCount, etc.
'
' Typical usage in a select query using a table (or query) as source:
'
' Select
' KeyField,
' DJoin("[ValueField]", "[Table]", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' The source can also be an SQL Select string:
'
' Select
' KeyField,
' DJoin("[ValueField]", "Select ValueField From SomeTable Order By SomeField", "[KeyField] = " & [KeyField] & "") As Values
' From
' Table
' Group By
' KeyField
'
' To clear the collection (cache), call DJoin with no arguments:
'
' DJoin
'
' Requires:
' CollectValues
'
' 2019-06-24, Cactus Data ApS, Gustav Brock
'
Public Function DJoin( _
Optional ByVal Expression As String, _
Optional ByVal Domain As String, _
Optional ByVal Criteria As String, _
Optional ByVal Delimiter As String = " ") _
As Variant
' Expected error codes to accept.
Const CannotAddKey As Long = 457
Const CannotReadKey As Long = 5
' SQL.
Const SqlMask As String = "Select {0} From {1} {2}"
Const SqlLead As String = "Select "
Const SubMask As String = "({0}) As T"
Const FilterMask As String = "Where {0}"
Static Values As New Collection
Dim Records As DAO.Recordset
Dim Sql As String
Dim SqlSub As String
Dim Filter As String
Dim Result As Variant
On Error GoTo Err_DJoin
If Expression = "" Then
' Erase the collection of keys.
Set Values = Nothing
Result = Null
Else
' Get the values.
' This will fail if the current criteria hasn't been added
' leaving Result empty.
Result = Values.Item(Criteria)
'
If IsEmpty(Result) Then
' The current criteria hasn't been added to the collection.
' Build SQL to lookup values.
If InStr(1, LTrim(Domain), SqlLead, vbTextCompare) = 1 Then
' Domain is an SQL expression.
SqlSub = Replace(SubMask, "{0}", Domain)
Else
' Domain is a table or query name.
SqlSub = Domain
End If
If Trim(Criteria) <> "" Then
' Build Where clause.
Filter = Replace(FilterMask, "{0}", Criteria)
End If
' Build final SQL.
Sql = Replace(Replace(Replace(SqlMask, "{0}", Expression), "{1}", SqlSub), "{2}", Filter)
' Look up the values to join.
Set Records = CurrentDb.OpenRecordset(Sql, dbOpenSnapshot)
CollectValues Records, Delimiter, Result
' Add the key and its joined values to the collection.
Values.Add Result, Criteria
End If
End If
' Return the joined values (or Null if none was found).
DJoin = Result
Exit_DJoin:
Exit Function
Err_DJoin:
Select Case Err
Case CannotAddKey
' Key is present, thus cannot be added again.
Resume Next
Case CannotReadKey
' Key is not present, thus cannot be read.
Resume Next
Case Else
' Some other error. Ignore.
Resume Exit_DJoin
End Select
End Function
' To be called from DJoin.
'
' Joins the content of the first field of a recordset to one string
' with a space as delimiter or an optional delimiter, returned by
' reference in parameter Result.
'
' 2019-06-11, Cactus Data ApS, Gustav Brock
'
Private Sub CollectValues( _
ByRef Records As DAO.Recordset, _
ByVal Delimiter As String, _
ByRef Result As Variant)
Dim SubRecords As DAO.Recordset
Dim Value As Variant
If Records.RecordCount > 0 Then
While Not Records.EOF
Value = Records.Fields(0).Value
If Records.Fields(0).IsComplex Then
' Multi-value field (or attachment field).
Set SubRecords = Records.Fields(0).Value
CollectValues SubRecords, Delimiter, Result
ElseIf Nz(Value) = "" Then
' Ignore Null values and zero-length strings.
ElseIf IsEmpty(Result) Then
' First value found.
Result = Value
Else
' Join subsequent values.
Result = Result & Delimiter & Value
End If
Records.MoveNext
Wend
Else
' No records found with the current criteria.
Result = Null
End If
Records.Close
End Sub
Full documentation can be found in my article:
Join (concat) values from one field from a table or query
If you don't have an account, browse to the link: Read the full article.
Code is also on GitHub: VBA.DJoin

How to round time to the nearest quarter hour in word

I need to round time to the nearest quarter hour in a word document. I am not very good at coding.
After a fair bit of searching I have found some vba code but it doesn't quite work. The code is:
Sub Time()
Dim num() As String
Dim tod() As String
Dim temp As String
num = Split(Time, ":")
tod = Split(num(2), " ")
If Val(num(1)) < 15 Then
temp = "00"
ElseIf Val(num(1)) < 30 Then
temp = "15"
ElseIf Val(num(1)) < 45 Then
temp = "30"
ElseIf Val(num(1)) < 60 Then
temp = "45"
End If
gettime = num(0) + ":" + temp + ":00 " + tod(1)
End Function
End Sub
When I try to run it I get a message:
"Compile Error: Expected function or variable"
and "Time" on the fifth line of the code is highlighted which I think is where the program stops running.
The rest of the code in the form is as follows:
This module doesn't affect the time rounding issue but I am including it so as not to leave anything out.
Option Explicit
Sub ClusterCheck()
Dim i As Integer, k As Integer, iCluster As Integer, bResult As Boolean
Dim sFieldNameNo As String, sName As String
On Error Resume Next ' If the first formfield is a checkbox, this will bypass the error that Word returns
sName = Selection.FormFields(1).Name ' Get the name of the formfield
bResult = ActiveDocument.FormFields(sName).CheckBox.Value ' Get the result of the current formfield
sFieldNameNo = Number(sName) ' Get generic number
sName = Left(sName, Len(sName) - Len(sFieldNameNo)) ' Get generic name
' Determine how many fields are within the cluster group
iCluster = 1
Do Until ActiveDocument.Bookmarks.Exists(sName & iCluster) = False
iCluster = iCluster + 1
Loop
iCluster = iCluster - 1
' If the check field is true, turn all of the other check fields to false
Application.ScreenUpdating = False
If bResult = True Then
For k = 1 To iCluster
If k <> sFieldNameNo Then ActiveDocument.FormFields(sName & k).Result = False
Next
End If
Application.ScreenUpdating = True
End Sub
This is the Number module:
Option Explicit
Function Number(ByVal sNumber As String) As String
' This module finds the form fields number within the field name
' Loops through the field name until it only has the number
Do Until IsNumeric(sNumber) = True Or sNumber = ""
sNumber = Right(sNumber, Len(sNumber) - 1)
Loop
Number = sNumber
End Function
This is the protection module:
Option Explicit
Sub Protect()
ActiveDocument.Protect Password:="wup13", NoReset:=True, Type:=wdAllowOnlyFormFields
End Sub
Sub Unprotect()
ActiveDocument.Unprotect Password:="wup13"
End Sub
This is the code that activates on opening and closing the document:
Option Explicit
Sub Document_Open()
' Zooms to page width, turns on Hidden Text, and turns off ShowAll and Table Gridlines
With ActiveWindow.View
.Zoom.PageFit = wdPageFitBestFit
.ShowHiddenText = True
.TableGridlines = False
.ShowAll = False
End With
Options.UpdateFieldsAtPrint = False
End Sub
Sub Document_Close()
' Turn on ShowAll and Table Gridlines
With ActiveWindow.View
.ShowAll = True
.TableGridlines = True
End With
Options.UpdateFieldsAtPrint = True
End Sub
That's all the code in the form. I am not great at VBA but am hoping I can solve this issue (with a little help).
DETAILS OF EXTRA DUTY FORM
Persons details
Family name:
Given name(s):
Level:
No.:
Location:
Cost Centre Code:
Time worked
Were any days of the extra duty performed on a designated public/show holiday? Yes 0 No 0
If yes enter holiday date/details:
Time commenced: [Text Form Field]
Date:
Time ceased: [Text Form Field]
Date:
Total Overtime claimed:
Are you a shift worker? Yes 0 No 0
Details of extra duty performed:
Vehicle details
Car: Yes 0 No 0
Motorcycle: Yes 0 No 0
Registration no.:
Fleet no.:
Stationary vehicle hours:
Yes 0 No 0 (only use for stationary duties)
Vehicle odometer start:
Odometer finish:
Total kms:
Client’s details
Company/Organisation name:
Phone no.:
Contact name:
Job no.:
Payment for special services
Was payment received in advance? Yes 0 No 0
If Yes– Amount:
Receipt no.:
Date:
If No– Amount:
Invoice no.:
Date:
I, , certify the above information to be true
(Signature) (Date)
Manager certification (Checked with roster and certified correct)
(Signature) (Date)
The code from vbforums gives me a subscript out of range error when used as recommended.
In the VBA IDE you can get explanations of what keywords do by placing the cursor on a keyword and pressing F1. This will bring up the MS help page for that particular keyword.
In the OP code the main procedure is 'Time'. This will cause problems for VBA because this is the same as the Time keyword so we would effectively be saying
time(time)
and VBA will stop with an error because the second use of time will be interpreted as the sub time and not the VBA time function so you will get the error message 'Argument not optional'.
The code below will provide what the OP has requested.
Option Explicit
Sub test_gettime()
Dim myTime As String
myTime = Now()
Debug.Print myTime
Debug.Print Format(myTime, "hh:mm:ss")
Debug.Print gettime(Format(myTime, "hh:mm:ss"))
' without the format statement we should also get the date
myTime = Now()
Debug.Print
Debug.Print myTime
Debug.Print gettime(myTime)
End Sub
Public Function gettime(this_time As String) As String
Dim myTimeArray() As String
Dim myQuarterHour As String
myTimeArray = Split(this_time, ":")
' Note that myTimeArray has not been converted to numbers
' Comparison of strings works by comparing the ascii values of each character
' in turn until the requested logic is satisfied
Select Case myTimeArray(1)
Case Is < "15"
myQuarterHour = "00"
Case Is < "30"
myQuarterHour = "15"
Case Is < "45"
myQuarterHour = "30"
Case Is < "60"
myQuarterHour = "45"
Case Else
Debug.Print "More than 60 minutes in the hour??"
End Select
gettime = myTimeArray(0) + ":" + myQuarterHour + ":00 "
End Function

how to add search criteria for a range of values in msaccess 2003

I am using the code below to filter a query to return values entered in search fields on a form.
how can I modify the code, to allow my user to search for records with values greater than or less than a number in the search field.
for example the user enters 60 as the [OD] - I want the code to return records with an [OD] between 55 and 65 ([60] +/- 5).
since i'm using the addtowhere function below, I don't know how to modify this code.
can anyone help?
Public Sub cmdSearch_Click()
' Create a WHERE clause using search criteria entered by user and
' set RecordSource property of SEARCH QUOTE SUBform.
If Me.[Goodsinsub].Form.Recordset.RecordCount = 0 Then Me.Goodsinsub.Form.Command95.Visible = False Else Me.Goodsinsub.Form.Command95.Visible = True
Dim MySQL As String, MyCriteria As String, myrecordsource As String
Dim ArgCount As Integer
Dim tmp As Variant
Dim mycontrol As Control
' Initialize argument count.
ArgCount = 0
' Initialize SELECT statement.
MySQL = "SELECT * FROM [qry_tubes out] WHERE"
MyCriteria = ""
' Use values entered in text boxes in form header to create criteria for WHERE clause.
AddToWhere [Combo30], "[product]", MyCriteria, ArgCount
AddToWhere [OD], "[OD]", MyCriteria, ArgCount
AddToWhere [ID], "[ID]", MyCriteria, ArgCount
AddToWhere [LG], "[LG]", MyCriteria, ArgCount
' If no criterion specifed, return all records.
If MyCriteria = "" Then
MyCriteria = "True"
End If
' Create SELECT statement.
myrecordsource = MySQL & MyCriteria
' Set RecordSource property of Find Customers Subform.
Me![Goodsinsub].Form.RecordSource = myrecordsource
' If no records match criteria, display message.
' Move focus to Clear button.
If Me![Goodsinsub].Form.RecordsetClone.RecordCount = 0 Then
tmp = EnableControls("detail", True)
MsgBox "No records found"
Else
' Enable control in detail section.
tmp = EnableControls("Detail", True)
' Move insertion point to Find Customers Subform.
Me![Goodsinsub].Visible = True
End If
End Sub
the user enters 60 as the [OD] - I want the code to return records
with an [OD] between 55 and 65 ([60] +/- 5).
You can use Abs for this:
Where Abs([Enter OD] - [OD]) <= 5