Let's make the default member calls and keywords explicit:
Public Function transform([ByRef] inputRange As Range) As Range
[Let] transform.[_Default] = inputRange.[_Default]
End Function
Because of the missing Set
keyword, the RHS Range
is being Let
-coerced into the LHS, which becomes the victim of an implicit default member assignment.
The right-hand side of the assignment is not a Range
, it's a Variant
that's either a single value or a 2D variant array, depending on what inputRange
is: the function is computing to #VALUE!
because it runs into a type mismatch error when it attempts to assign that Variant
(RHS) to a Range
reference (LHS) - you can experience this by typing ?transform([A1])
in the immediate pane (Ctrl+G).
If you mean the function to return a Range
object reference, you need a Set
keyword there - note that inputRange
can be passed by value:
Public Function transform(ByVal inputRange As Range) As Range
Set transform = inputRange
End Function
Now, with that said, a function that returns a Range
can't be used as-is in a worksheet - you have to wrap it with, say, an INDEX
function, at least if what you're returning isn't a single value: a UDF cannot modify any cells in the sheet: it returns a value.
You're looking for the TRANSPOSE
function.
UPDATE
You can display your results in the excel sheet as below, as explained here:
First select some blank cells. But make sure to select the same number of cells required to be returned by the function, both horizontally and vertically
With those blank cells still selected, type your function, like: =transform(
Now type the range of the cells you want to manipulate, so the formula would be something like =transform(A1:B2)
-- but don't press ENTER yet! Just stop typing, and go to the next step.
Finally, press CTRL+SHIFT+ENTER
Your VBA function for doing so, could be:
Public Function transform(inputRange As Range) As Variant()
x = inputRange.rows.Count
y = inputRange.Columns.Count
Dim oldArray() As Variant, newArray() As Variant
ReDim oldArray(1 To x, 1 To y), newArray(1 To y, 1 To x)
oldArray = inputRange.Value
For i = 1 To x
For j = 1 To y
newArray(j, i) = oldArray(i, j)
Next
Next
transform = newArray
End Function