Converting a Variant to a Double Array in Visual Basic

Updated Nov 8, 2022

Environment

Software

  • Measurement Studio (Legacy)
  • Measurement Studio Standard

Programming Language

  • Visual Basic .NET

How can I convert a variant to a double array in In Microsoft Visual Basic?

There are several ways to do this in either VB6 or VB .NET, depending on if the double array is given an initial size or not.

If the double array is declared without a size:

Dim d() as double

then you can use the CopyArray method to copy a variant array to this array of doubles. The CopyArray function returns the variant as an array of doubles. This method will also work with multidimensional arrays.

If the double array is declared with a size:

Dim d(5) as double

then you will not be able to use the CopyArray method. In this case, you'll need to loop through the elements of the variant array to copy the values into a double array.

Additional Information

An example for the first method, using CopyArray, is given below.
  1. Open a new project in Visual Basic and paste the following code into the form.
  2. Add watches on v and d and hit F8 to step through the code. Notice that this example builds a variant array and then copies that array to d.
Private Sub Form_Load()
    Dim v(0 To 4) As Variant
    Dim d() As Double
    Dim i As Long
    
    For i = 0 To 4
        v(i) = 3.456  'dummy floating point number to fill array with
    Next i
    
    d = CWArray1.CopyArray(v)
End Sub

Note: The CopyArray method will always return the array as 0 indexed, even if the original array was indexed with something else. If you need the array to be indexed by 1, you can use the ReshapeArray method.