Results 1 to 6 of 6

Thread: Variable-length Arrays

  1. #1

    Thread Starter
    Member
    Join Date
    May 2002
    Posts
    45

    Variable-length Arrays

    I have another easy question which seems rather difficult to find the answer to. I would like to define an array to be the size of the length of a recordset that I have taken from my database.

    The problem is, when I declare an array like this:

    Dim MyArray(intCount) as integer
    (or something like that)

    It tells me that it wants a constant. I know this is possible in C based languages, but I'm unsure of how it works in VB. Any insight?


    Mat

  2. #2
    PowerPoster cafeenman's Avatar
    Join Date
    Mar 2002
    Location
    Florida
    Posts
    2,819
    you can declare an array one of two ways. Either with a subscript (fixed) or with no subscript (dynamic)

    VB Code:
    1. Const MyNum As Long = 12
    2.  
    3. Dim Arr1(MyNum) As String
    4. Dim Arr2(12) As String
    5. Dim Arr3() As String
    6.  
    7. Sub SomeSub()
    8.  
    9. Redim Preserve Arr3(4358345)
    10.  
    11. End Sub

  3. #3

    Thread Starter
    Member
    Join Date
    May 2002
    Posts
    45

    Still curious

    Now, would MyNum in your first example be able to be defined like this:

    Dim MyInt as Long
    MyInt = 12
    Const MyNum As Long = MyInt
    Dim Arr1(MyNum) As String

    Would that work?

    And second question, when you define the array dynamically, can you then ReDim it with a variable?

    So:

    Dim Arr3() As String
    Sub SomeSub()
    Dim MyNum as Integer
    MyNum = 4358345
    Redim Preserve Arr3(MyNum)
    End Sub

    Would either of those two work?

    Thanks,


    Mat

  4. #4
    PowerPoster cafeenman's Avatar
    Join Date
    Mar 2002
    Location
    Florida
    Posts
    2,819
    yes
    yes

  5. #5

    Thread Starter
    Member
    Join Date
    May 2002
    Posts
    45

    Thanks

    Thats exactly what I needed. Thanks very much.


    Mat

  6. #6
    PowerPoster cafeenman's Avatar
    Join Date
    Mar 2002
    Location
    Florida
    Posts
    2,819

    Re: Thanks

    Originally posted by MattyJ
    Thats exactly what I needed. Thanks very much.


    Mat
    If you just use ReDim then the contents of the array are erased. For numbers that means all array elements become 0. For strings they all become an empty string (vbNullString).

    If you want to preserve the contents of the array, use ReDim Preserve.

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