3

I have a cell whose value is an array constant, for example cell A1 is set to ={1,2,3,4,5,6}

I then defined a function in VBA:

Function MyFunc(Data)
MyFunc = Data.Rows.Count
End Function

I want the function to return the length of the array (6) when I can =MyFunc(A1), but using the debugger, I find the 'Data' variable my function receives only contains the first element of this array. Data.Rows.Count evaluates to 1 and TypeName(Data) evaluates to 'Range'

1
  • 1
    Data is not an array, but a Range object. Range.Value is an array only if the range is for more than a single cell. Commented Jun 19, 2019 at 17:13

3 Answers 3

5

And another method:

Function myFunc(Data)
    myFunc = UBound(Evaluate(Data.Formula))
End Function
Sign up to request clarification or add additional context in comments.

Comments

3

I'm not sure what your use case is, but I think you can just use Split here.

Function MyFunc(ByVal Data As Range) As Long
    Dim x
    x = Split(Data.Formula, ",")
    MyFunc = UBound(x) + 1
End Function

enter image description here

Obviously this can be made more robust (e.g. handle a multi-cell input), but I think it gets you going in the right direction.

2 Comments

I think that hard-coded comma needs to be Application.International(xlListSeparator).
@MathieuGuindon I agree, add that to the list of things that "can be made more robust" :)
3

May be

Function MyFunc(data As Range)
Dim x

x = Split(Mid(data.Formula, 3), ",")
MyFunc = UBound(x) + 1
End Function

1 Comment

I think that hard-coded comma needs to be Application.International(xlListSeparator).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.