Results 1 to 3 of 3

Thread: Classic VB - General - What are arrays and how do I use them?

  1. #1

    Thread Starter
    No place like 127.0.0.1 eyeRmonkey's Avatar
    Join Date
    Jul 2005
    Location
    Blissful Oblivion
    Posts
    2,306

    Classic VB - General - What are arrays and how do I use them?

    Arrays are a useful feature of any programming language. They allow you to store a lot of data in a systematic format. When combined with loops, they become an extremely powerful tool.

    Things you should know before hand:
    * How to declare a variable
    * How to join two strings together
    * How to use loops
    * How to type


    So lets get cracking...

    The Basics
    When you declare a variable the normal way, it would like this:
    VB Code:
    1. Dim MyVariable As String
    ... this is just one variable and has 1 place in the memory of the computer. Now, suppose you want a lot of strings that will all be holding similar information. Maybe it is a list of email addresses. How would you store all these? You could do this:
    VB Code:
    1. Dim EmailA As String
    2. Dim EmailB As String
    3. Dim EmailC As String
    4. ' And so on...
    But that is very sloppy and hard to work with because if you want to do some work with those email address you have to do it to each one and end up using copy-paste a lot. Now when you declare it like this:
    VB Code:
    1. Dim Email(8) As String
    ... you are telling the computer that you want 9 strings put into memory. It is 9 because arrays start counting at 0 by default so you have 0 through 8. The number in parenthesis tells the computer how many you want to make. From here on out, where ever we put a number in parenthesis it will be referring to a specific item out of the 9 we have declared (also called an element). So if we did this:
    VB Code:
    1. Dim Email(8) As String
    2.  
    3. ' Now we store strings into each of the elements in the array
    4. ' Email(0) just means we want to deal with the first element
    5. ' of the "Email" array
    6. Email(0) = "bob@example.com"
    7. Email(1) = "steve@example.org"
    8. Email(2) = "blah@example.net"
    9. ' ... and so on. up to
    10. Email(8) = "jessica@example.com"
    that would be the equivalent of doing this (without arrays):
    VB Code:
    1. Dim EmailA As String, Dim EmailB As String, Dim EmailC As String
    2. Dim EmailD As String, Dim EmailE As String, Dim EmailF As String
    3. Dim EmailG As String, Dim EmailH As String, Dim EmailI As String
    4.  
    5. EmailA = "bob@example.com"
    6. EmailB = "steve@example.org"
    7. EmailC = "blah@example.net"
    8. ' ...
    9. EmailI = "jessica@example.com"

    Putting Arrays to Work
    So far the only advantages of arrays that we have seen is that they are easier to declare because you don't have to write out each variable.

    Now, say we wanted to string all of these together and print them to a text box. Here is how we would do it the bad way (without arrays):
    VB Code:
    1. ' Assume we have already declared and stored values
    2. ' into the variables in the last code example
    3.  
    4. Dim Output As String
    5.  
    6. ' String together the emails and add a space after each
    7. Output = Output & EmailA & " "
    8. ' Output currently holds: [email]bob@example.com[/email]
    9. Output = Output & EmailB & " "
    10. ' Output currently holds: [email]bob@example.com[/email] [email]steve@example.org[/email]
    11. ' ...
    12. Output = Output & EmailI & " "
    13. ' Output should hold all 9 email address with a space between them, but
    14. ' it took a lot of code to get there.
    That is obviously very redundant coding and would get to be a pain in the butt very quickly. Luckily we have arrays available to use and we can do it like this:
    VB Code:
    1. ' Assume we have already put value into the array as
    2. ' we did 3 code boxes ago.
    3. Dim i As Long
    4. Dim sOutput As String
    5.  
    6. ' Loop 9 times
    7. For i = 0 To 8
    8.     sOutput = sOutput & Email(i) & " "
    9. Next i
    That does the exact same thing as the last code box, but with much less code.

    Clearing The Array
    Now, if you want to erase an array before you continue using it there are two methods you can use. The first is fairly straight forward:
    VB Code:
    1. Erase Email()
    This simply sets every value in the back to an empty string. It would be the same as doing this (without arrays):
    VB Code:
    1. EmailA = ""
    2. EmailB = ""
    3. ' ...
    4. EmailC = ""

    The other way to clear the contents of an array is to use the "ReDim" statement as so:
    VB Code:
    1. ReDim Email(8)
    The only difference is that you put a number in the parenthesis. This number must be the length of your array just like when you originally declared it.

    Erase is easier when you simply want to clear an array, but ReDim has a lot more power than simply clearing an array. We can't go over all of the functionality of ReDim here, but I hope to write a "Advanced Arrays" tutorial in the near future, so keep your eyes open.

    With this new knowledge under your belt, you can go out into the world and tackle some major problems with some relatively simple code. If you have any questions on this subject feel free to post them in the Classic VB Forum.
    Last edited by eyeRmonkey; Nov 25th, 2005 at 01:36 PM.

  2. #2
    Frenzied Member DKenny's Avatar
    Join Date
    Sep 2005
    Location
    on the good ship oblivion..
    Posts
    1,171

    Re: Classic VB - General - What are arrays and how do I use them?

    Quote Originally Posted by eyeRmonkey
    VB Code:
    1. For i = 0 To 8
    2.     sOutput = sOutput & Email(i) & " "
    3. Next i
    eyeRmonkey - Great FAQ but I just have one comment on the above. This assumes that the Option Base statement has been set to 0 and that there are always going to be 9 elements in the array. I think it is always safe to use the following syntax when looping through an array
    VB Code:
    1. For i = LBound(Email) To UBound(Email)
    2.     sOutput = sOutput & Email(i) & " "
    3. Next i
    Using this method you can be agnostic to both the Option Base statement and to the size of the array.
    Last edited by si_the_geek; Feb 7th, 2006 at 10:01 AM.

  3. #3
    Frenzied Member DKenny's Avatar
    Join Date
    Sep 2005
    Location
    on the good ship oblivion..
    Posts
    1,171

    Re: Classic VB - General - What are arrays and how do I use them?

    One question that is often asked is "How do I sort an array?"
    Here is a procedure that can be used to sort a multiple column array. As this procedure uses a basic bubble sort it should not be used for really large arrays.
    VB Code:
    1. ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
    2. ' Comments:     This procedure sorts an array based on a column
    3. '               number, in either ascending or descending order.
    4. '
    5. ' Arguments:    OldArray    The array to be sorted
    6. '               ColNum      An optional column number for 2d
    7. '                           arrays.
    8. '               ASC         An optional boolean value to sort
    9. '                           in ASCending or descending order.
    10. '
    11. ' Date          Developer       Action
    12. ' --------------------------------------------------------------
    13. ' 09/04/05      Declan Kenny    Initial version
    14. '
    15. Sub SortArray(ByRef OldArray As Variant, Optional ByVal ColNum As Integer = 1, Optional ByVal ASC As Boolean = True)
    16.  
    17. Dim Sorted As Boolean
    18. Dim ArrayRec As Integer
    19. Dim temp As Variant
    20. Dim ColCount As Integer
    21.    
    22.     'Loop until the Array is sorted
    23.     Do While Not Sorted
    24.        
    25.         'Assume the array is in the correct order
    26.         Sorted = True
    27.        
    28.         'Determine the sort order
    29.         If ASC Then
    30.            
    31.             'Loop through the Array
    32.             For ArrayRec = 1 To UBound(OldArray, ColNum) - 1
    33.                
    34.                 'Are the current element and the next element in the wrong order
    35.                 If OldArray(ArrayRec, ColNum) > OldArray(ArrayRec + 1, ColNum) Then
    36.                    
    37.                     'If so, then swap the rows
    38.                     For ColCount = 1 To UBound(OldArray, 2)
    39.                         temp = OldArray(ArrayRec + 1, ColCount)
    40.                         OldArray(ArrayRec + 1, ColCount) = OldArray(ArrayRec, ColCount)
    41.                         OldArray(ArrayRec, ColCount) = temp
    42.                     Next ColCount
    43.                    
    44.                     'Record that we are not sorted
    45.                     Sorted = False
    46.                 End If
    47.             Next ArrayRec
    48.        
    49.         'For Sorting in Descending Order
    50.         Else
    51.              
    52.              'Loop through the Array
    53.             For ArrayRec = 2 To UBound(OldArray, ColNum)
    54.                
    55.                 'Are the current element and the next element in the wrong order
    56.                 If OldArray(ArrayRec, ColNum) > OldArray(ArrayRec - 1, ColNum) Then
    57.                    
    58.                     'If so, then swap the rows
    59.                     For ColCount = 1 To UBound(OldArray, 2)
    60.                         temp = OldArray(ArrayRec - 1, ColCount)
    61.                         OldArray(ArrayRec - 1, ColCount) = OldArray(ArrayRec, ColCount)
    62.                         OldArray(ArrayRec, ColCount) = temp
    63.                     Next ColCount
    64.                    
    65.                     'Record that we are not sorted
    66.                     Sorted = False
    67.                 End If
    68.             Next ArrayRec
    69.         End If
    70.     Loop
    71. End Sub
    Last edited by DKenny; Apr 21st, 2006 at 02:35 PM.
    Declan

    Don't forget to mark your Thread as resolved.
    Take a moment to rate posts that you think are helpful

Posting Permissions

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



Click Here to Expand Forum to Full Width