When developing relational database applications, you often need to use list boxes or combo boxes to store records with alphanumeric keys. You can load numeric keys into the ItemData array of combo boxes and list boxes as Long integers. Programmers traditionally store alphanumeric keys in a String array with the index of the array elements stored in ItemData. However, for four-character, alphanumeric keys, avoid the overhead of an array by using CodeCrypt to convert the key into a Long integer.
CodeCrypt accepts a variant and returns a variant. If a four-character string is received, then CodeCrypt converts it to a Long integer. Each character, in turn, is converted to its ASCII value. The value in CodeCrypt is multiplied by 256 to shift the current value left by one byte. The ASCII value is then added to CodeCrypt (filling the empty low-order byte). Because a Long integer is made up of 32 bits (four bytes), up to four characters can now be stored in ItemData. If CodeCrypt receives a Long integer, the process is reversed and a string is returned:
Function CodeCrypt(pvInput As Variant) As Variant Dim i As Integer, temp As Long If UCase(TypeName(pvInput)) = "LONG" Then temp = pvInput Do While temp > 0 CodeCrypt = Chr$(temp Mod 256) & CodeCrypt temp = CLng(temp / 256) Loop Else If Len(pvInput) > 4 Then Exit Function For i = 1 To Len(pvInput) CodeCrypt = CodeCrypt * 256 + _ Asc(UCase$(Mid$(pvInput, i, 1))) Next i End IfEnd Function
Use this code to add alphanumeric code to lstBox.ItemData:
lstBox.AddItem textlstBox.ItemData(lstBox.NewIndex) = CodeCrypt(code)
Use this code to get alphanumeric code back from lstBox.ItemData:
sCode = CodeCrypt(lstBox.ItemData(lstBox.ListIndex))
This routine is unable to deal with strings whose first character is greater than Chr$(127).