Results 1 to 8 of 8

Thread: Inserting an element into an array (RESOLVED)

Hybrid View

  1. #1
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,803

    Re: Inserting an element into an array (RESOLVED)

    Quote Originally Posted by jemidiah
    Thanks for the suggestions, wish there was a way but apparently there isn't.
    No one said it's not possible, we just said that it is not recommended... and that there are better ways to do it.

    This is an example of how it's done for your original question:
    VB Code:
    1. Option Explicit
    2.  
    3. Private Type tStruct
    4.     Str As String
    5.     DT As Date
    6. End Type
    7.  
    8. Private ArrType() As tStruct
    9.  
    10. Private Sub Form_Load()
    11.     Dim InsertType As tStruct
    12.     Dim K As Long
    13.    
    14.     ReDim ArrType(1)
    15.    
    16.     ArrType(0).DT = #4/1/2005#
    17.     ArrType(0).Str = "Hello world..."
    18.    
    19.     ArrType(1).DT = #5/1/2005#
    20.     ArrType(1).Str = "blah blah 1"
    21.    
    22.     InsertType.DT = #6/1/2005#
    23.     InsertType.Str = "blah blah 2"
    24.    
    25.     InsertStructure ArrType, InsertType, 1
    26.    
    27.     For K = 0 To UBound(ArrType)
    28.         Debug.Print K, ArrType(K).DT, ArrType(K).Str
    29.     Next K
    30. End Sub
    31.  
    32. Private Sub InsertStructure(Arr() As tStruct, Insert As tStruct, Index As Long)
    33.     Dim K As Long
    34.     ReDim Preserve Arr(UBound(Arr) + 1)
    35.    
    36.     For K = UBound(Arr) To Index + 1 Step -1
    37.         Arr(K) = Arr(K - 1)
    38.     Next K
    39.    
    40.     Arr(Index) = Insert
    41. End Sub
    It works by re-sizing the array and then "shifting" all data up after the index you want to insert.
    This works fine for small arrays, but if you have a lot of data, you will see that it is a significant decrease in processing using this method.

    The way I said first, using a collection of classes it is much faster when you have many records.

  2. #2
    PowerPoster
    Join Date
    Feb 2002
    Location
    Canada, Toronto
    Posts
    5,803

    Re: Inserting an element into an array (RESOLVED)

    PS, this is a related thread you might be interested in:
    http://www.vbforums.com/showthread.php?t=327833

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