Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB4,VB5,VB6
Expertise: beginner
Oct 23, 1999

Quickly initialize Variant and String arrays

Visual Basic doesn't provide any way to declare an array and initialize its elements at the same time. In most cases you end up with setting individual elements one by one, as in:

Dim strArray(0 To 3) As String
strArray(0) = "Spring"
strArray(1) = "Summer"
strArray(2) = "Fall"
strArray(3) = "Winter"
Under VB4, VB5, and VB6 you can create an array of Variants on the fly, using the Array() function:

Dim varArray() As Variant
varArray() = Array("Spring", "Summer", "Fall", "Winter")
but there is no similar function to create arrays of data types other than Variant. If you're using VB6, however, you can create String arrays using the Split() function:

Dim varArray() As String
' arrays returned by Split are always zero-based
varArray() = Split("Spring;Summer;Fall;Winter", ";")
Under VB6 you can also take advantage of the capability for a Function to return an array, and build your own array initialization routines, such as the following one:

Function ArrayInt(ParamArray values() As Variant) As Integer()
    Dim i As Long
    ReDim res(0 To UBound(values)) As Integer
    For i = 0 To UBound(values)
        res(i) = values(i)
    ArrayInt = res()
End Function
You could also build a routine that tests the type of values passed to it, and returns an array of the correct type. In this case, the function should be declared to return a Variant.
Francesco Balena
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date