0

hello guys I hope you can help me with this one. I wrote a simple function to convert returns to prices. It is useless, but I will use it explain my problem. The function works. It does what I want.

Function ret2prices(ByVal r As Range)

    Dim temp() As Variant
    temp = r

    Dim prices() As Variant
    ReDim prices(1 To (UBound(temp, 1) + 1), 1)
    prices(1, 1) = 1

    For i = 2 To UBound(prices, 1)
        prices(i, 1) = 1 + temp(i - 1, 1)
        prices(i, 1) = prices(i - 1, 1) * prices(i, 1)
    Next i

    ret2prices = prices

End Function

the problem is that when I use it in excel worksheet it always returns 0. I would like to be able to use it the same way I use MMULT with CTRL + SHIFT + ENTER. Any suggestion?

thank you very much for your time

5
  • 2
    Second dimension of prices should be 1 To 1, now it's 0 To 1 and function returns array with 2 columns. Commented Nov 26, 2016 at 13:06
  • 1
    try to use your array for a range with 2 columns with CSE and you will see that @BrakNicku is right Commented Nov 26, 2016 at 13:34
  • I am sorry guys I didn't get your point Commented Nov 26, 2016 at 14:27
  • 2
    Change appropriate line to ReDim prices(1 To (UBound(temp, 1) + 1), 1 To 1) Commented Nov 26, 2016 at 14:32
  • Ohhh .. what an idiot ... I completely forgot that I had to specify the starting index for the second dimension too .. Now it works just fine. Thank you very much ... since we are here do you know if it is possible to refer to an entire column or row of an array ? Commented Nov 26, 2016 at 14:46

1 Answer 1

3

Arrays in VBA are 0-based, so:

ReDim prices(1 To (UBound(temp, 1) + 1), 1)

is equivalent to

ReDim prices(1 To (UBound(temp, 1) + 1), 0 To 1)

The code in question returned expected results, but in the second column of result array. Changing lower bound of second dimension to 1 fixes the problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Option Base 1 would also fix it. I general I don't like Option Base 1, but if all arrays in a given module are designed to transfer data between VBA and ranges, it is perhaps a valid use case.

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.