在sub中,调用包含循环的自写函数时,如何避免循环内重复使用函数输入的复杂性?

In a sub, when calling a self-written function that includes a loop, how to avoid the complication of the re-use of function inputs within the loop?

函数的计算是在循环中实现的,最后函数被设置为等于循环得到的数组。该功能工作正常。但是,当我将 sub 写入 return 数组(并再次将输入定义为范围)时出现错误,因为之前在循环中的函数中使用了输入,我的猜测是 sub 将其视为被覆盖.

Function discount_factors(swap_rates As Range) As Variant

    Dim swap_matrix(1 To 5, 1 To 5) As Double

For i = 1 To 5
    For j = 1 To 5
        swap_matrix(i, j) = 0
    Next j
Next i

For i = 1 To 5
    For j = 1 To 5 - i
        swap_matrix(i + j, i) = swap_rates(j + i, 1)
    Next j
    swap_matrix(i, i) = 1 + swap_rates(i, 1)
Next i

inverse_matrix = Application.WorksheetFunction.MInverse(swap_matrix)


Dim df(1 To 5, 1 To 1) As Double

For i = 1 To 5
    df(i, 1) = 0
    For j = 1 To 5
        df(i, 1) = df(i, 1) + inverse_matrix(i, j)
    Next j
Next i

discount_factors=df

End Function




Sub result()

Dim swap_rates As Range

inputs = Sheet1.Range("A7:B11").Value

Sheet1.Range("C7:C11")=discount_factors(swap_rates)

End Sub

当我 运行 它时,它调试并跳转到第一个循环,指的是我假设输入中使用的 swap_rates 的维度已经改变。我该如何解决这个问题,让我的子 运行 没有这种并发症?

我试过你的代码,如果我的想法是正确的,你只需要修改一些地方:

Sub result()

     Dim swap_rates As Range

     Set swap_rates = Sheet1.Range("A7:B11")

     Sheet1.Range("C7:C11") = discount_factors(swap_rates)

End Sub

它对我有用,但我不知道它是否是你想要的。 :)