How to Change Payback Macro to Payback Function

Barklie

Board Regular
Joined
Jul 4, 2013
Messages
86
Hi all,

I have made a macro for calculating payback for an investment using a one dimensional array of cash flows. The problem is I would like this to be a function where the user can just select an array and the macro will run automatically using the range that user has provided and output the payback for them.

I am attaching the macro I currently use, where I have to manually set the range. If anyone knows anyway this can be made into a function, please let me know. Thanks!

Code:
Sub Payback()

On Error Resume Next

Dim R As Range

Set R = Range("I2:I15")

CumCF = 0
i = 0

For Each C In R
    If CumCF <= 0 Then
        CumCF = CumCF + C.Value
        Pybck = i + 1 - (CumCF / R.Cells(i + 1))
    End If
    i = i + 1
Next

Range("C3") = Pybck

End Sub
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
I don't know what your input data look like so there's no error trapping in this. This can be used directly in a worksheet cell or called from a macro.
Code:
Function Payback(R As Range)
Dim C As Range
CumCF = 0
i = 0
For Each C In R
    If CumCF <= 0 Then
        CumCF = CumCF + C.Value
        Pybck = i + 1 - (CumCF / R.Cells(i + 1))
    End If
    i = i + 1
Next
Payback = Pybck
End Function
 
Upvote 0

Forum statistics

Threads
1,223,957
Messages
6,175,625
Members
452,661
Latest member
Nonhle

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top