Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

1. ## Visual Basic Question

What is the most efficient way to alphabetize words in order?

For example, an user puts 3 names of animals in 3 textboxes. The program will put them in alphabetical order. My code is:

Private Sub cmdcalculate_Click()
Dim Animal1 As String 'These are going to be the variables
Dim Animal2 As String 'used throughout the whole program
Dim Animal3 As String
Dim Temp As String 'temporary storage
Dim Result As Integer
Dim Result2 As Integer
Dim Result3 As Integer

Animal1 = txtA1 'get strings from boxes
Animal2 = txtA2 ' and assign to variables
Animal3 = txtA3

Result = StrComp(Animal1, Animal2, 1)
Result2 = StrComp(Animal1, Animal3, 1)
Result3 = StrComp(Animal2, Animal3, 1)

If Result = -1 And Result3 = -1 Then
Temp = Animal1 & " " & Animal2

txtAnswer.Text = Temp & " " & Animal3

Else: Temp = Animal1 & " " & Animal2
txtAnswer.Text = Animal3 & " " & Temp
End If

If Result = 1 And Result2 = 1 And Result3 = -1 Then
txtAnswer.Text = Animal2 & " " & Animal3 & " " & Animal1

ElseIf Result = 1 And Result2 = -1 And Result3 = -1 Then
txtAnswer.Text = Animal2 & " " & Animal1 & " " & Animal3

ElseIf Result3 = 1 And Result = 1 And Result2 = 1 then
txtAnswer.Text = Animal3 & " " & Animal2 & " " & Animal1

ElseIf Result = -1 And Result2 = 1 And Result3 = 1 Then
txtAnswer.Text = Animal3 & " " & Animal1 & " " & Animal2

End If

cmdClear.SetFocus
End Sub

It works, but it doesn't seem the most efficient way. Any help?

2. Since you are dealing with a fixed number of strings to alphabatize, this way seems to function the best.

3. don't know if its efficient, but you can create a disconnected recordset with all the strings in it and then use the sort method to alphabetize

4. Well if you were using a database, you could just use SQL to return the values from the database in alphabetical order.

5. The easiest and painless way to do it is to use a LISTBOX control, set the the following properties of the listbox to:

VISIBLE = FALSE -- so user will not see it
SORTED = TRUE -- so items will be sorted

Then your code will look like this:

These items will be added to the list box in alphabetical order, to retrieve the items:

For i = 0 to List1.ListCount
Msgbox List1.List(i)
Next

Thanks,
Ray

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•