devxlogo

Quickly initialize Variant and String arrays

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 StringstrArray(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 VariantvarArray() = 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-basedvarArray() = 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)    Next    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.

See also  Digital Signage Solutions for Agile Software Development Teams
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist