Ranges and Arrays – 2

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
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")
.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.

This entry was posted in Arrays, Excel, UDFs. Bookmark the permalink.

One Response to Ranges and Arrays – 2

  1. Pingback: Writing an array to a worksheet range - correction « Newton Excel Bach, not (just) an Excel Blog

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s