View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
Jim Cone[_2_] Jim Cone[_2_] is offline
external usenet poster
 
Posts: 1,549
Default Excel VBA Array Function...What's wrong?

I cleaned up your function and also provided a shorter version...
'--

'Used to call the functions - "2" and "22"
Sub TestTheRangeFunctions()
Dim x As Variant
x = Range22Array(Selection)
MsgBox x(3, 2)

x = Range2Array(Selection)
MsgBox x(3, 2)
End Sub
'-----------

Function Range2Array(ByRef Source As Range) As Variant
Dim rowCount As Long
Dim colCount As Long
Dim Result() As Variant
Dim i As Long
Dim j As Long

If TypeName(Selection) < "Range" Then Exit Function
rowCount = Source.Rows.Count
colCount = Source.Columns.Count
ReDim Result(1 To rowCount, 1 To colCount) As Variant

'Load result array
For i = 1 To rowCount
For j = 1 To colCount
Result(i, j) = Source(i, j).Value
Next j
Next i
'Return result array
Range2Array = Result
End Function
'--

'The shorter version...
Function Range22Array(ByRef Source As Range) As Variant
Dim Result As Variant
If TypeName(Selection) < "Range" Then Exit Function
Result = Source.Value
Range22Array = Result
End Function
--
Jim Cone
Portland, Oregon USA




"Spatters71"
wrote in message
I am just trying to create an array function that returns an array containing
the values in a source Range. It shouldn't be that difficult, right? My
source is below. I am running into the problem on this line: "Result(i, j) =
Source(i, j).Value". The Result element is Empty after the assignment, even
though Source(i,j).Value is not Empty. Help!? If you know why this assignment
isn't working or if you know a better way to do this, please let me know.

Function Range2Array(Source As Range) As Variant
Dim rowCount, colCount As Integer
rowCount = Source.Rows.count
colCount = Source.Columns.count
' Ensure target is a range equal in size to source
If Not (TypeOf Application.Caller Is Range _
And Application.Caller.Columns.count = colCount _
And Application.Caller.Rows.count = rowCount _
) Then
Exit Function
End If
' Load result array
Dim Result() As Variant
ReDim Result(1 To rowCount, 1 To colCount) As Variant
Dim i, j As Integer
Result(1, 1) = "Test"
For i = 1 To rowCount
For j = 1 To colCount
' At this point Source(i,j).Value is not Empty
Result(i, j) = Source(i, j).Value
' At this point the value of Result is Empty.
Next j
Next i
' Return result array
Test = Result
End Function