Excel-VBA:需要一个函数来从一个范围中选择每个第二个值

时间:2017-04-25 20:18:34

标签: excel-vba vba excel

我有一个用户定义的函数,它通过采用两个参数来计算投资回收期:支出和一系列流入。

Public Function PayBackPeriod(outlay, inflow)
Dim i, yr As Integer
Dim cTotal As Double ' cumulative total
cTotal = 0

    For i = 1 To inflow.Count


    cTotal = cTotal + inflow.Cells(i).Value


    If cTotal = Abs(outlay) Then
    PayBackPeriod = i
    Exit Function
    End If
    If cTotal > Abs(outlay) Then
     yr = i - 1
     cTotal = cTotal - inflow.Cells(i).Value
     PayBackPeriod = yr + (Abs(outlay) - (cTotal)) / inflow.Cells(i).Value

     Exit Function

    End If
    Next i
    PayBackPeriod = "Not enough return to Payback!!!"

现在问题是我的流入范围有一个美元金额和一个百分比,所以我真的需要提取每一秒的价值。我尝试在行后添加“第2步”:

'cTotal = cTotal + inflow.Cells(i).Value Step 2`

但这似乎不起作用......有人能指出我正确的方向吗?提前致谢... enter image description here

1 个答案:

答案 0 :(得分:0)

而不是遍历Cells,而不是Rows上的循环(假设inflow是n行x 2 cols范围)

For i = 1 To inflow.Rows.Count

    'work with inflow.Rows(i)

Next i

如果您的输入是2行x n列:

For i = 1 To inflow.Columns.Count

    'work with inflow.Columns(i)

Next i