如何将动态分配的数组传递到Excel VBA中的函数中

问题描述 投票:0回答:1

我对Excel VBA非常了解,因此请您谅解。在互联网上进行研究并没有解决我的问题。因此,我希望将VBA中的一组数字值传递给函数,也就是将现金流量全部输入Excel VBA代码中的NPV函数。

Dim Postavke() As String, velikost As Integer, i As Integer

velikost = WorksheetFunction.CountA(Worksheets("List1").Columns(11))

ReDim Postavke(velikost)

For i = 1 To velikost
    Postavke(i) = Cells(i + 1, 11).Value
Next i

现在我想将Postavke()数组传递给NPV函数:

Dim NSV As Long

NSV = NPV(0.06, ByRef Postavke() As Long))

总是出错。是否对如何实现有任何想法?

谢谢你。最好的问候。

arrays excel vba function pass-by-reference
1个回答
1
投票

以这种方式创建函数:

Function NPV(whatever As Double, Postavke() As String) As Long
    Dim x As Long
    'do whatever you want with your code, work on the 'x' variable and finally ends with:
    NPV = x
    'or define NPV earier and use Exit Function after..
End Function

您必须决定是否必须将Postavke()数组声明为字符串或长整数。我保留了你最初的声明。并像这样调用函数:

NSV = NPV(0.06, Postavke())

为了正确加载从1开始的velikost,您必须在模块代码的顶部添加:

Option Base 1

否则,您必须注意(如@SJR所示)默认情况下该数组是从零开始的。

© www.soinside.com 2019 - 2024. All rights reserved.