PDA

View Full Version : Solved: CAGR formula using only range as input



greglittle
09-27-2012, 11:41 AM
Can someone please check this formula to see why I keep getting a #VALUE error when I use it in the sheet? Thanks!


Function CAGR(rng As Range) As Double
Dim firstCell As Range
Dim lastCell As Range
Dim firstVal As Double
Dim lastVal As Double

firstCell = rng.Cells(1, 1)
lastCell = rng.Cells(1, rng.Count)
firstVal = Range(firstCell).Value
lastVal = Range(lastCell).Value

Debug.Print firstCell, lastCell, firstVal, lastVal

CAGR = (lastVal / firstVal) ^ (1 / rng.Count) - 1

End Function


Also, does anyone know how to use Debug.Print to see what the values of the variables are for a function (like this) that is used as a formula in the sheet? I've never had the need to see variable values in this case (and it didn't work!).

CatDaddy
09-27-2012, 02:22 PM
put a breakpoint in the program before the line "CAGR = ..." then when you hover over the variables with the mouse it will tell you their values

Paul_Hossler
09-27-2012, 04:27 PM
I think that since firstCell and lastCell are already Ranges, you don't want to use Range(firstCell)

Probably something like this


firstCell = rng.Cells(1, 1)
lastCell = rng.Cells(1, rng.Count)
firstVal = firstCell.Value
lastVal = lastCell.Value




Paul

greglittle
09-27-2012, 06:51 PM
@CatDaddy, I inserted a breakpoint, but none of the variables have values. Since firstVal and lastVal depend on firstCell and lastCell parsing the range info correctly, there must be something wrong with my use of ".Cells(x,y)" in the following part:


firstCell = rng.Cells(1, 1)
lastCell = rng.Cells(1, rng.Count)

Any thoughts?


@Paul, good point, but that still didn't resolve the error. Any other ideas?

Thanks!

Paul_Hossler
09-27-2012, 07:05 PM
Any other ideas?


Might be the way you're calling it then

Can you post a small WB showing the problem?

Paul

greglittle
09-27-2012, 07:27 PM
Here you go.

abdulla
09-28-2012, 05:12 AM
Try it now

Function CAGR(rng As Range) As Double
Dim firstval As Double
Dim lastval As Double
firstval = rng.Cells(1, 1).Value
lastval = rng.Cells(1, rng.Columns.Count).Value
CAGR = (lastval / firstval) ^ (1 / rng.Columns.Count) - 1
End Function

greglittle
09-28-2012, 10:43 AM
Thanks! Based on your solution, I'm not sure why mine didn't work (especially since firstCell and lastCell are ranges). But, even so, your code is more efficient anyway. Take care!