Yesterday we looked at how to get data from a worksheet range into a VBA array. Today’s post looks at the opposite operation; writing an array to a worksheet range.
With a UDF it couldn’t be simpler:
Function MyFunction() as Variant
Dim MyArray() as double
...
MyFunction = MyArray
End Function
This function will return whatever was in MyArray. To access all this data there are several options:
The easy way is to enter the function in the worksheet as an array function; i.e. enter the function as normal (array element (1,1) will display), then select the range where you want to display the array (with the function in the top-left cell); press the F2 key to enter edit mode; then press Ctrl-Shift-Enter to enter the array as an array function. The contents of the array will be displayed, with NA in any cells outside the limits of the array.
To display one element, or a limited range, of the array, use the Index() worksheet function; e.g. =Index(MyFunction(),2 ,3) will display the array element for row 2, column 3; i.e. =Index() works on arrays in exactly the same way as it works on worksheet ranges.
Finally you can code optional output index parameters in your UDF, so selected elements of the array can be displayed without using =Index():
Function MyFunction(Parameter1, Parameter2, Optional Out1 as long, Optional Out2 as long) as Variant
Dim MyArray() as double
...
If Out1 = 0 Then
MyFunction = MyArray
Else
MyFunction = MyArray(Out1, Out2)
End If
End Function
With an array in a VBA subroutine it is a similar procedure. The code below will adjust the size of an existing named range to the size of the array, then write the array values to the range:
ReDim myarray(1 To NumArrayRows, 1 To NumArrayColumns)
' Fill array
With Range("MyNamedRange")
.ClearContents
.Resize(NumArrayRows, NumArrayColumns).Name = "MyNamedRange"
End With
Range("MyNamedRange").Value2 = myarray
Anyone who has used a loop to write an array to a worksheet range, cell by cell, will appreciate the dramatic increase in speed using this method.
Pingback: Writing an array to a worksheet range - correction « Newton Excel Bach, not (just) an Excel Blog