Share via

Problem with a Sort Code

Anonymous
2023-11-22T16:48:58+00:00

I have a sort code that sorts the case number field and puts it into numeric order since the field in a text field. The code is as follows:

Public Function CaseNumberSort(vntCaseNum) As String

On Error GoTo ErrorHandler 

Dim strCaseNum As String 

Dim lngSortNum As Long 

Dim strZeroPad As String 

Dim intIdx As Integer 

Dim strSortCode As String 

strSortCode = "" 

strZeroPad = String(15, "0")    ' Used to pad with leading zeros 

If IsNull(vntCaseNum) Then 

    ' Case Number is null. 

    GoTo ExitHandler 

End If 

strCaseNum = Trim(CStr(vntCaseNum)) 

If strCaseNum = "" Then 

    ' Case Number is blanks or empty string. 

    GoTo ExitHandler 

End If 

If IsNumeric(Left(strCaseNum, 1)) Then 

    ' Case Number begins with numeric digits. 

    lngSortNum = Val(strCaseNum) 

    ' Pad with leading 0's so that it sorts properly. 

    strSortCode = Right(strZeroPad & lngSortNum, Len(strZeroPad)) 

    ' Append the original Case Number to the sort code. 

    strSortCode = strSortCode & strCaseNum 

    ' We're done. 

    GoTo ExitHandler 

End If 

Next intIdx

ExitHandler:

CaseNumberSort = strSortCode 

Exit Function 

ErrorHandler:

GoTo ExitHandler 

End Function

I have the code in a query to sort the case number field. When I run the query, it does not put the numbers in proper order after 999. It placed 23-1000 after 23-100.

Microsoft 365 and Office | Access | For business | Windows

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous
2023-11-22T18:29:23+00:00

Sort the query by the following expressions, each of which returns a numerical value:

ORDER BY Val(CaseNo), Val(Mid(CaseNo,Instr(CaseNo,"-")+1))

You can see how the expressions work in the immediate window:

CaseNo = "23-1000"

Sort1 = Val(CaseNo)

? Sort1

 23

Sort2 = Val(Mid(CaseNo,Instr(CaseNo,"-")+1))

? Sort2

 1000

BTW avoid special characters like the # character or spaces in object names.  They can cause notational problems.  Instead use CamelCase as I've done above, or represent a space with an underscore character, e.g. Case_No.

Was this answer helpful?

1 person found this answer helpful.
0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Anonymous
    2023-11-22T18:04:23+00:00

    Where and how do I add this to the code?

    Was this answer helpful?

    0 comments No comments
  2. Tom van Stiphout 40,211 Reputation points MVP Volunteer Moderator
    2023-11-22T17:48:36+00:00

    You could enhance your function by finding the "-" using the InStr function, and then pad the second number with leading zeros if <1000.

    Was this answer helpful?

    0 comments No comments