Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

i'm writing an vba function in excel which takes in an odd sized empty square matrix and filling it with numbers. However, I can't get to retrieve the size of the array that it dynamically selected in the spreadsheet before the function is called. How would I do this?

Thanks!

share|improve this question
1  
Can you show us exactly what do you mean by dynamically selected in the spreadsheet before the function is called. – Siddharth Rout Aug 19 '12 at 18:30
a wild stab in the dark: x = UBound(MyArray, 2) – Reafidy Aug 20 '12 at 6:55

1 Answer

Pass a Range object into your function and look at the value:

Public Function WhatIsTheMatrix(SourceRange as Excel.Range) As Variant

   Dim arrSource as Variant
   Dim arrOutPut as Variant

   Dim i As LongDim j As Long

   arrSource = SourceRange.Value2

   i = Ubound(arrSource, 1)
   j = Ubound(arrSource, 2)

   ' The lower bounds of an array obtained from a range are always 1

   ' code
   ' more code
   ' even more code

   WhatIsTheMatrix = arrOutPut 

End Function

Now you have two problems:

  1. Your original problem, which is solved by inspecting i and j

  2. A special case, in which the value of a single-cell range isn't an array variant

So you'll need this:

If SourceRange.Cells.Count = 1 Then
   Redim arrSource(1 to 1, 1 To 1)
   arrSource(1,1) = SourceRange.Value2
Else
   arrSource = SourceRange.Value2
End If

Any other Business:

There's an unrecognized assumption, namely: you thought you could pass in the current Application.Selection and it will always be a range. It can also be a control, or a chart, or a chart series...

...And no, you can't rely on this raising a runtime error for the type mismatch. Yes, you've invoked Option Explicit and yes, you typed SourceRange as Excel.Range and your Mother, your Parish Priest and a Justice of the Peace watched you do it; try sacrificing something on a sinister-looking rock after midnight, and maybe the VBA runtime will believe you.

So you also need this:

If Not TypeOf SourceRange Is Excel.Range Then
   ' Raise an error or Exit Sub
End If

I think that's all the surprises. Unless you're into exotic stuff and awkward questions like "Is this range calculated?"

share|improve this answer
You might want to deal with the possibility of the selection being a Range with multiple Areas. This method will return the dimensions of the first area only (which isn't necessarily the wrong approach) – barrowc Jul 3 at 0:20

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.