How do I set dynamic array with no upper limit which allows additions to the array?

I have a sub which I want to use to track some ID(s) dynamically.  Want to declare array and then be able to add values to it dynamically below is my attempt but keep getting subscript out of range error.

Dim IDNr As Integer
Dim Cnt As Integer
Dim StudentID
StudentID = Array()
IDNr = txtID
Cnt = UBound(StudentID) + 1
StudentID(Cnt) = IDNr

Long on points short on talent.  Need fast help.
mbartAsked:
Who is Participating?
 
Harisha M GCommented:
Private Sub Form_Load()
Dim IDNr As Integer
Dim TotalScore As Integer
Dim StudentAvg As Double
Dim StudentID
IDNr = CInt(txtID)
Dim arr() As Integer
ReDim arr(0)                                          '<-- Add this line
ReDim Preserve arr(UBound(arr) + 1)
arr(UBound(arr)) = StudentID
Debug.Print arr(UBound(arr))

End Sub
0
 
Harisha M GCommented:
Hi mbart,
    Dim arr() As Integer

    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = IDNr1

    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = IDNr2

    ....

Bye
---
Harish
0
 
ZylochCommented:
Hi mbart,

I am not specializing in VB, so I wouldn't know if there is a better way, but why don't you do this?

im IDNr As Integer
Dim Cnt As Integer
Dim StudentID
StudentID = Array()
IDNr = txtID
Cnt = Ubound(StudentID)+1
ReDim StudentID(Cnt)
StudentID(Cnt) = IDNr

I don't know how effective this is, but by searching around, I also found this site which may be interesting: http://www.aspheute.com/english/20001025.asp


Regards,
Zyloch
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
ZylochCommented:
Oops, my bad, didn't see your response, and I forgot the Preserve lol

Regards...
0
 
Harisha M GCommented:
No problem ;-)
0
 
mbartAuthor Commented:
Thanks for the quick help. Let me try it.
0
 
mbartAuthor Commented:
Here is my code which still throws subscript error

Dim IDNr As Integer
Dim TotalScore As Integer
Dim StudentAvg As Double
Dim StudentID
IDNr = CInt(txtID)
Dim arr() As Integer
ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = StudentID
Debug.Print arr(UBound(arr))

What did i miss?
0
 
mbartAuthor Commented:
Worked!! Thanks for the help
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.