473,395 Members | 1,647 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Sorting alphanumeric values

7
Hello everyone,

I have a file in which i need to sort a database extract based on an alphanummerical column. The column is set to text to ensure it doesnt sort numbers before text, which works well.

However, a problem arises when users 'neglect' to input 1A as 01A;
Excel sorts my file as follows: 10A, 10B, 11C, 19A, 1A, 20A, 2A, MM10, MM11, MM1
In stead of the desired: 1A, 2A, 10A, 10B, 11C, 19A, 20A, MM1, MM10, MM11.

If the user inputs 01A in stead of 1A it works fine, but sadly i dont have this control to enforce it in the system it's input into.

Does anyone know a solution to this problem?

Kind regards,

Oxydo
Jan 5 '12 #1

✓ answered by ADezii

If I understand you correctly, your non-formatted Data now resides in a Temporary Table. Let's assume that this Table Name is tblTEMP, and that the Field that needs to run through the Function to be properly Formatted is [Field1]. A simple Update Query will subsequently leave [Field1] in tblTEMP in the proper State. The SQL would be:
Expand|Select|Wrap|Line Numbers
  1. UPDATE tblTEMP SET tblTEMP.Field1 = fAnalyzeAlphaNumeric([Field1])

10 2653
Rabbit
12,516 Expert Mod 8TB
Prepend the 0 character to the ones that are missing it.
Jan 5 '12 #2
Oxydo
7
@Rabbit
Hi Rabbit,

I was thinking along the same lines. However, how do i put this in a formula? If i just add an 0 to everything it wont work, and the amount of possibilities (to search and replace or crosstab) is staggering (1A to 1ZZZ).

My other option would be to change the sortorder (is this possible) from 0123456789abcdef.. to abcdef0123456789.

Best regards,

Oxydo
Jan 5 '12 #3
Rabbit
12,516 Expert Mod 8TB
You can't change the sort order like that. But you can grab the first two characters, check if it's numeric, if it's not, that means it's missing the 0 character, and then prepend it.
Jan 5 '12 #4
ADezii
8,834 Expert 8TB
Expand|Select|Wrap|Line Numbers
  1. Public Function fAnalyzeAlphaNumeric(strBaseString As String) As String
  2. Select Case Val(Left$(strBaseString, 1))
  3.   Case 1 To 9       'The 1st Character is a Number between 1 and 9
  4.     'Is the 2nd Character an Alpha?
  5.     If Asc(Mid$(UCase$(strBaseString), 2, 1)) >= 65 And _
  6.        Asc(Mid$(UCase$(strBaseString), 2, 1)) <= 90 Then
  7.       strBaseString = "0" & strBaseString
  8.     Else    '1st Character 1 to 9, 2nd is Non-Alpha
  9.       strBaseString = strBaseString
  10.     End If
  11.   Case Else    '1st Character not 1 to 9
  12.     strBaseString = strBaseString
  13. End Select
  14.  
  15. fAnalyzeAlphaNumeric = strBaseString
  16. End Function
Expand|Select|Wrap|Line Numbers
  1. Debug.Print fAnalyzeAlphaNumeric("Hello World")
  2. Returns: 'Hello World'
Expand|Select|Wrap|Line Numbers
  1. Debug.Print fAnalyzeAlphaNumeric("1A")
  2. Returns: '01A'
Expand|Select|Wrap|Line Numbers
  1. Debug.Print fAnalyzeAlphaNumeric("55B")
  2. Returns: '55B'
Expand|Select|Wrap|Line Numbers
  1. Debug.Print fAnalyzeAlphaNumeric("1ZZZZZZ")
  2. Returns: '01ZZZZZZ'
Jan 6 '12 #5
Oxydo
7
Thanks for your reply ADezzi. I've tried to implement it into my code for extracting a DB to excel, then manipulating it. Sadly I'm now getting an invalid procedure error on the line;

Expand|Select|Wrap|Line Numbers
  1.     If Asc(Mid(UCase(strbasestring), 2, 1)) >= 65 And _
  2.        Asc(Mid(UCase(strbasestring), 2, 1)) <= 90 Then
  3.  
This is how i've added it to my code (the procedure is being called starting from line 116).

Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2.  
  3. Sub tellijstvest()
  4.  
  5. ' ***
  6. ' *** Declareer de namen en typen van objecten en variabelen
  7. ' ***
  8.  
  9. Dim qdf As DAO.QueryDef
  10. Dim dbs As DAO.Database
  11. Dim rstTel As DAO.Recordset
  12. Dim xlx As Object, xlw As Object, xls As Object, xlc As Object
  13. Dim blnheaderrow As Boolean, blnexcel As Boolean
  14. Dim lngcolumn As Long, lastrow As Long
  15. Dim strTemp As String, strx As String, strSQL As String, strTel As String, strBestandspad As String, strWorksheetnaam As String, strVestiging As String, strbasestring As String
  16. ' *** De tijdelijke query wordt zExporttellijst genoemd.
  17. Const strTempQueryName As String = "zExportTellijst"
  18. ' *** Variabele dbs wordt gevuld met de gegevens van de huidige database
  19. Set dbs = CurrentDb
  20. ' *** Gebruiker wordt gevraagd het vestigingsnummer op te geven
  21. strVestiging = InputBox(Prompt:="Voor welke vestiging?", _
  22.         Title:="Vestigingsnummer")
  23. ' *** Vervang de cursor door een zandloper
  24. DoCmd.Hourglass True
  25. ' *** Het bestand wordt aangemaakt op de volgende locatie, met vestigingsnummer gevolgd door datum in de bestandsnaam.
  26. strBestandspad = "C:\test\" & Format(Now(), "yyyy") & "\" & Format(Now(), "MMM") & "\" & strVestiging & " " & Format(Now(), "MMdd") & ".xls"
  27. ' *** onbekende code om de query te initialiseren
  28. strTemp = dbs.TableDefs(0).Name
  29. strSQL = "SELECT * FROM [" & strTemp & "] where 1=0;"
  30. Set qdf = dbs.CreateQueryDef(strTempQueryName, strSQL)
  31. qdf.Close
  32. strTemp = strTempQueryName
  33.  
  34. ' ***
  35. ' *** Gegevens ophalen
  36. ' ***
  37. ' *** alle regels en kolommen met het betreffende vestigingsnummer worden in een recordset opgeslagen
  38. strSQL = "SELECT Kenteken, Naam, Artikel, Maat, Mk, Type, LV, RV, LA, RA, Locatie, Datum, Aantal from tbl_dbs_klantenbanden WHERE " & "Ves = " & strVestiging & ";"
  39. Set rstTel = dbs.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
  40. ' *** de eerste regel bevat kolomkoppen
  41. blnheaderrow = True
  42. ' ***
  43. ' *** Excel bestand opstellen
  44. ' ***
  45. 'hier wordt een excel bestand gemaakt
  46. On Error Resume Next
  47. Set xlx = GetObject(, "Excel.Application")
  48. If Err.Number <> 0 Then
  49.     Set xlx = CreateObject("Excel.Application")
  50.     blnexcel = True
  51. End If
  52. Err.Clear
  53. On Error GoTo 0
  54. xlx.Visible = False
  55. ' *** Nieuw werkboek wordt gemaakt, met het vestigingsnummer als naam.
  56. Set xlw = xlx.workbooks.Add
  57. Set xls = xlw.worksheets(1)
  58. xls.Name = strVestiging
  59. ' *** Excel begint in veld A1
  60. xls.Application.DisplayAlerts = False
  61. Set xlc = xls.Range("A1")
  62. ' *** als er gegevens in de recordset staan worden deze naar excel geschreven
  63. If rstTel.EOF = False And rstTel.BOF = False Then
  64. ' *** eerst de header
  65.     For lngcolumn = 0 To rstTel.Fields.Count - 1
  66.         xlc.offset(0, lngcolumn).Value = rstTel.Fields(lngcolumn).Name
  67. ' *** door naar de volgende
  68.     Next lngcolumn
  69.     Set xlc = xlc.offset(1, 0)
  70. xlc.copyfromrecordset rstTel
  71. End If
  72. ' ***
  73. ' *** Het excel bestand krijgt formatting
  74. ' ***
  75. ' *** Aantal rijen wordt opgeslagen in variabele lastrow
  76. lastrow = xls.Range("B65535").End(xlUp).Row - 1
  77. ' *** Print op elke pagina de header
  78. xls.PageSetup.PrintTitleRows = "$1:$1"
  79. ' *** Vervang de artikelcodes door Zomer / Winter
  80. xls.Range("C:C").Replace What:="51500", Replacement:="WINTER", LookAt:=xlPart, _
  81.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  82.         ReplaceFormat:=False
  83. xls.Range("C:C").Replace What:="51502", Replacement:="WINTER", LookAt:=xlPart, _
  84.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  85.         ReplaceFormat:=False
  86. xls.Range("C:C").Replace What:="51503", Replacement:="ZOMER", LookAt:=xlPart, _
  87.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  88.         ReplaceFormat:=False
  89. xls.Range("C:C").Replace What:="51501", Replacement:="ZOMER", LookAt:=xlPart, _
  90.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  91.         ReplaceFormat:=False
  92. ' *** verwijder bepaalde symbolen uit de locatie zodat de sortering beter verloopt
  93. xls.Range("K:K").Replace What:=".", Replacement:="", LookAt:=xlPart, _
  94.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  95.         ReplaceFormat:=False
  96. xls.Range("K:K").Replace What:=":", Replacement:="", LookAt:=xlPart, _
  97.         SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
  98.         ReplaceFormat:=False
  99. ' *** Voeg een tijdelijke kolom toe met formule om kenteken en art.groep samen te voegen.
  100. xls.Columns("A").Insert
  101. xls.Range("A2").FormulaR1C1 = "=CONCATENATE(RC[1],RC[3])"
  102. xls.Range("A2").Copy Destination:=xls.Range("A2").Resize(lastrow, 1)
  103. ' *** Zet de waarde ZW achter elke regel die zowel zomer als winterbanden heeft liggen in de vestiging
  104. xls.Range("O1").Value = "ZW"
  105. xls.Range("O2").FormulaR1C1 = "=IF(SUMIF(C[-13],RC[-13],C[-1])>SUMIF(C[-14],RC[-14],C[-1]),""ZW"","""")"
  106. xls.Range("O2").Copy Destination:=xls.Range("O2").Resize(lastrow, 1)
  107. ' *** zet de waarde >4 achter elke regel die meer dan 4 banden heeft liggen in de vestiging
  108. xls.Range("P1").Value = ">4"
  109. xls.Range("P2").FormulaR1C1 = "=IF(SUMIF(C[-14],RC[-14],C[-2])>4,"">4"","""")"
  110. xls.Range("P2").Copy Destination:=xls.Range("P2").Resize(lastrow, 1)
  111. ' *** vervang de formules door normale tekst
  112. xls.Range("A:P") = xls.Range("A:P").Value
  113. ' *** verwijder de tijdelijke kolom
  114. xls.Columns("A").Delete
  115. xls.Columns("K").NumberFormat = "@"
  116. Dim rngLocatie As Range
  117. For Each xlc In xls.Range("K:K")
  118. fAnalyzeAlphaNumeric (xlc.Value)
  119. xlc.Value = strbasestring
  120. Next
  121. ' *** Automatisch aanpassen van de kolombreedte
  122. xls.Columns("A:S").EntireColumn.AutoFit
  123. ' ***
  124. ' *** De variabelen worden geleegd en bestanden gesloten
  125. ' ***
  126. xls.Application.DisplayAlerts = False
  127. rstTel.Close
  128. Set rstTel = Nothing
  129. Set xlc = Nothing
  130. Set xls = Nothing
  131. xlw.saveas strBestandspad
  132. xlw.Close False
  133. Set xlw = Nothing
  134. If blnexcel = True Then xlx.Quit
  135. Set xlx = Nothing
  136. dbs.QueryDefs.Delete strTemp
  137. dbs.Close
  138. Set dbs = Nothing
  139. DoCmd.Hourglass False
  140. End Sub
  141.  
  142. Public Function fAnalyzeAlphaNumeric(strbasestring As String) As String
  143. Select Case Val(Left$(strbasestring, 1))
  144.   Case 1 To 9       'The 1st Character is a Number between 1 and 9
  145.     'Is the 2nd Character an Alpha?
  146.     If Asc(Mid(UCase(strbasestring), 2, 1)) >= 65 And _
  147.        Asc(Mid(UCase(strbasestring), 2, 1)) <= 90 Then
  148.       strbasestring = "0" & strbasestring
  149.     Else    '1st Character 1 to 9, 2nd is Non-Alpha
  150.       strbasestring = strbasestring
  151.     End If
  152.   Case Else    '1st Character not 1 to 9
  153.     strbasestring = strbasestring
  154. End Select
  155.  
  156. fAnalyzeAlphaNumeric = strbasestring
  157. End Function
  158.  
Any further pointers would be appreciated.

Regards,

Oxydo
Jan 6 '12 #6
ADezii
8,834 Expert 8TB
It appears as though you are using Automation Code to Open an Instances of Excel, populate a Worksheet with Data, than pass all Values within a specific Range to an Access Function for evaluation and return.

Run an Update Query in Access to provide the desired Values, then base the rstTel Recordset on the Fields with these Updated Values.

P.S. - It is also possible that the Function is receiving Zero Length Strings, Strings of Length < 2, or NULL Values. In either one of these cases, the Logic will fail. I modified the Code and added a Band Aid to see if will possibly work with these adjustments.
Expand|Select|Wrap|Line Numbers
  1. Public Function fAnalyzeAlphaNumeric(varBaseString As Variant) As Variant
  2. If IsNull(varBaseString) Then
  3.   fAnalyzeAlphaNumeric = Null
  4.     Exit Function
  5. ElseIf Len(varBaseString) < 2 Then
  6.   fAnalyzeAlphaNumeric = varBaseString
  7.     Exit Function
  8. End If
  9.  
  10. Select Case Val(Left$(varBaseString, 1))
  11.   Case 1 To 9       'The 1st Character is a Number between 1 and 9
  12.     If Asc(Mid$(UCase$(varBaseString), 2, 1)) >= 65 And _
  13.        Asc(Mid$(UCase$(varBaseString), 2, 1)) <= 90 Then
  14.       varBaseString = "0" & varBaseString
  15.     Else
  16.       varBaseString = varBaseString
  17.     End If
  18.   Case Else
  19.     varBaseString = varBaseString
  20. End Select
  21.  
  22. fAnalyzeAlphaNumeric = varBaseString
  23. End Function
Jan 6 '12 #7
Oxydo
7
Hi Adezzi,

Since receiving your reply i've changed my code around somewhat to do most of the work in access itself, to be able to use your function. I'm now at the point where the data is put through a make table query, and stored in a temporary db.

At this point in the code i would like to call your function, but im not sure how.



Expand|Select|Wrap|Line Numbers
  1. Sub tellijstvest()
  2.  
  3. ' ***
  4. ' *** Declareer de namen en typen van objecten en variabelen
  5. ' ***
  6.  
  7. Dim qdf As DAO.QueryDef
  8. Dim dbs As DAO.Database
  9. Dim rstTel As DAO.Recordset
  10. Dim xlx As Object, xlw As Object, xls As Object, xlc As Object
  11. Dim blnheaderrow As Boolean, blnexcel As Boolean
  12. Dim lngcolumn As Long, lastrow As Long
  13. Dim strTemp As String, strx As String, strSQL As String, strTel As String, strBestandspad As String, strWorksheetnaam As String, strVestiging As String, strbasestring As String
  14. ' *** De tijdelijke query wordt zExporttellijst genoemd.
  15. Const strTempDBSName As String = "zExportTellijst"
  16. ' *** Variabele dbs wordt gevuld met de gegevens van de huidige database
  17. Set dbs = CurrentDb
  18. ' *** Gebruiker wordt gevraagd het vestigingsnummer op te geven
  19. strVestiging = InputBox(Prompt:="Voor welke vestiging?", _
  20.         Title:="Vestigingsnummer")
  21. ' *** Vervang de cursor door een zandloper
  22. 'DoCmd.Hourglass True
  23. ' *** Het bestand wordt aangemaakt op de volgende locatie, met vestigingsnummer gevolgd door datum in de bestandsnaam.
  24. strBestandspad = "C:\test\" & Format(Now(), "yyyy") & "\" & Format(Now(), "MMM") & "\" & strVestiging & " " & Format(Now(), "MMdd") & ".xls"
  25. ' *** onbekende code om de query te initialiseren
  26. strTemp = dbs.TableDefs(0).Name
  27. strSQL = "Select Kenteken, Naam, Artikel, Maat, Mk, Type, LV, RV, LA, RA, Locatie, Datum, Aantal into ztbl_tellijst From tbl_dbs_klantenbanden where " & " Ves = " & strVestiging & ";"
  28. Set qdf = dbs.CreateQueryDef(strTempDBSName, strSQL)
  29. qdf.Execute
  30.  
  31. .....
  32.  

COuld you provide me with yet another great help?

Kind regards,

Oxydo
Jan 7 '12 #8
ADezii
8,834 Expert 8TB
If I understand you correctly, your non-formatted Data now resides in a Temporary Table. Let's assume that this Table Name is tblTEMP, and that the Field that needs to run through the Function to be properly Formatted is [Field1]. A simple Update Query will subsequently leave [Field1] in tblTEMP in the proper State. The SQL would be:
Expand|Select|Wrap|Line Numbers
  1. UPDATE tblTEMP SET tblTEMP.Field1 = fAnalyzeAlphaNumeric([Field1])
Jan 7 '12 #9
Oxydo
7
Works great, thanks a lot!

Regards,

Oxydo
Jan 8 '12 #10
ADezii
8,834 Expert 8TB
You are quite welcome, Oxydo.
Jan 8 '12 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

5
by: Rakesh | last post by:
Hi, For a particular problem of mine, I want to sort <key, value> pairs by its value. Eg: Input: A, 4 B, 5
3
by: parksch2 | last post by:
I have been trying and trying to properly sort records through a mySQL query. I have hour, minute and AM/PM values stored separately in a database as varchars. I'm trying to concat those, cast them...
10
by: Bob | last post by:
Sorting the following alphanumerics using myArray.sort(): 04-273-0001 04-272-0001 04-272-0003 04-272-0001 04-273-0001 Results in:
1
by: VMI | last post by:
How can I sort a table column correctly when the table has values like "0", "A1", "AA-1", "B21", "3C", 4-32A", "1", "11-1", 2-A", etc... The table will then be loaded to a grid and that's when...
3
by: John Smith | last post by:
Hello all: New problem. I am currently storing some mostly numeric values as ids in a db but with the possiblity that there are revisions to each. For instance say we have a record such as...
2
by: jediknight | last post by:
Hi, I have a listview which has columns of text and columns of numerical data. I need to be able to sort these columns into ascending/desending order whenever the user clicks on the column...
3
by: symbee | last post by:
Hi all, I want to create a string of alphanumeric values. Actually it is for security purpose. I am using C++ and I want the fuction for that... Can anybody help regarding this?? Plzzzzzzzzzzz...
7
by: pt36 | last post by:
Hi I have a php string like this: $string = "one two three four five" I have to sorting the values randomly every time the page are loaded. So, for example: first time "one two three four five"...
1
by: reni | last post by:
haii, plzz help me to arrange the userid in ascending order, the userid contains both numeric and alphanumeric values, i am using vb dot net2005 and sql2000, when i arrange the userid it is coming...
1
by: MGM | last post by:
Hey everyone, I had a quick problem: I want to be able to send a string of data to a function and have it return that same string but only in alphanumerics. That is to say, if I sent it: ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.