0

I want to create a function MyRange as follows:

Input: three numbers a,b,d
Output: an array of values from a to b with step size of d.

For example, if A1 contains 1, and B1 contains 5, and you write =MyRange(A1,B1,1) in the cell C1 (and you type Ctrl+Shift+Enter) you get:

 A | B | C | D | E | F | G
 -------------------------
 1 | 5 | 1 | 2 | 3 | 4 | 5

Here's my trial:

Function MyRange(a, b, d)  
Dim Index As Integer, Number As Integer  
Dim Res() As Integer  
Index = 0  
For Number = a To b Step d  
   Res(Index) = Number
   Index = Index + 1  
Next Number
MyRange = Res
End Function

When I try this, Excel throws #VALUE! and I don't know what's the problem..

BTW yeah, I had a similar question before that got no answer, as it was too complicated, so I'd deleted it and simplified my question here.

3
  • this isn't full answer, but one thing you'll need to do to get your output is select C1:C[B+2] and enter the array formula with all these columns highlighted to get your output. Commented Sep 15, 2017 at 15:38
  • Are you entering it as an array formula? You are also not declaring the size of Res so need to use Redim.
    – SJR
    Commented Sep 15, 2017 at 15:41
  • @ScottHoltzman tnx, but even when I do it, Excel throws the same error
    – Dudi Frid
    Commented Sep 15, 2017 at 15:41

1 Answer 1

1

This bit of cleanup worked for me. Mainly, I adding the ReDim Preserve to keep adding dimensions to the array.

Function MyRange(a As Integer, b As Integer, d As Integer) As Integer()

    Dim Index As Integer, Number As Integer
    Dim Res() As Integer

    Index = 0

    For Number = a To b Step d

        ReDim Preserve Res(Index)
        Res(Index) = Number
        Index = Index + 1

    Next Number

    MyRange = Res

End Function

The problem you will have is with how many columns to select over from C to enter your formula. This will depend on d/b.

2
  • how could I generalize it to handle the case where a,b,d are Integer() rather than just Integer?
    – Dudi Frid
    Commented Sep 16, 2017 at 8:16
  • @DudiFrid - if you want to pass array's into the arguments write (a() as Integer, b() as Integer ...) Commented Sep 16, 2017 at 17:13

Your Answer

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

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