Option Explicit
'Data array
Private MyArray() As Variant
'Column identifiers
Private Const NUMBER = 0
Private Const X3_CHAR_CODE = 1
Private Const X10_CHAR_STRING = 2
'Enum for output textbox
Private Enum TextType
TXT_ORIGINAL_ARRAY = 0
TXT_SORTED_ARRAY = 1
End Enum
Private Sub btnCreateArray_Click()
'Counter
Dim i As Integer
'Dim array
ReDim MyArray(2, 5)
'Fill array
For i = 0 To (UBound(MyArray, 2) - 1)
MyArray(NUMBER, i) = CInt(rnd * 100)
MyArray(X3_CHAR_CODE, i) = Chr((rnd * 25) + 65) & Chr((rnd * 25) + 65) & Chr((rnd * 25) + 65)
MyArray(X10_CHAR_STRING, i) = Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31) & Chr((rnd * 94) + 31)
Next
'Display original array
Call DisplayArray(TXT_ORIGINAL_ARRAY)
'Enable sort buttons
btnSortArray.Enabled = True
End Sub
'Uses bubble sort method
Private Sub btnSortArray_Click()
'Counters
Dim i As Long
Dim j As Long
Dim n As Long
Dim allOk As Boolean
'Temp array - should be same size as 1 record of MyArray
ReDim tempN(UBound(MyArray, 1)) As Variant
'Set sort column value
Dim SC As Integer
SC = CInt(txtColumn.Text)
'Check sort column boundary
If ((SC < 0) Or (SC > UBound(MyArray, 1))) Then
MsgBox ("Invalid sort column entered.")
Exit Sub
End If
'Sort array by first column
For n = 0 To UBound(MyArray, 2)
allOk = True
For i = 0 To UBound(MyArray, 2) - 1
If MyArray(SC, i) > MyArray(SC, i + 1) Then
allOk = False
'Get temp element
For j = 0 To UBound(tempN)
tempN(j) = MyArray(j, i)
MyArray(j, i) = MyArray(j, i + 1)
MyArray(j, i + 1) = tempN(j)
Next
End If
Next
If allOk Then Exit For
Next
'Display sorted array
Call DisplayArray(TXT_SORTED_ARRAY)
End Sub
Private Sub DisplayArray(TT As TextType)
'Clear chosen textbox
txtArrayOutput(TT).Text = ""
'Display array on chosen textbox
Dim i As Integer
For i = TT To (UBound(MyArray, 2) - (1 - TT))
txtArrayOutput(TT).Text = txtArrayOutput(TT).Text & _
CStr(MyArray(NUMBER, i)) & " : " & _
CStr(MyArray(X3_CHAR_CODE, i)) & " : " & _
CStr(MyArray(X10_CHAR_STRING, i)) & vbNewLine
Next
End Sub
Private Sub txtColumn_KeyPress(KeyAscii As Integer)
'Disallow non-numeric entries
If ((KeyAscii < vbKey0) Or (KeyAscii > vbKey9)) Then
If (KeyAscii <> vbKeyBack) Then KeyAscii = 0
End If
End Sub