簡體   English   中英

VBA Excel - 將數組傳遞給函數

[英]VBA Excel - passing an array into a function

我想編寫一個可以包含數組的函數。 我想該函數將像函數 NPV 一樣工作,我們有 3 種方法可以在公式欄中指定語法:

1) NPV(0.5, A1:A5)
2) NPV(0.5, A1, A2, A3, A4, A5)
3) NPV(0.5, {10, 20, 23, 25, 27})

其中 10、20、23、25、27 是 A1:A5 范圍內的值。

這是我在 VBA 中的函數:

Function MyNpv(r As Double, Flows As Variant)

Dim i, n As Integer
Dim p As Double
n = Application.Count(Flows)
For i = 1 To n
 p = p + Flows(i) / (r + 1) ^ i
Next i

MyNpv = p

End Function

但是,我自己的功能只能像這樣工作:

MyNpv(0.5, A1:A5)

無論如何,我可以聲明我的數組,以便它像函數 NPV 一樣靈活地工作嗎?

謝謝。

使用ParamArray ,循環它來測試數組的每個部分中的內容,然后相應地調整:

Function MyNpv(r As Double, ParamArray Flows() As Variant)

    Dim FlowsPart As Variant

    Dim p As Double
    p = 0#

    Dim k As Long
    k = 1

    For Each FlowsPart In Flows
        Dim arr As Variant
        arr = FlowsPart

        Dim x As Long
        x = -1

        Dim y As Long
        y = -1

        On Error Resume Next
            x = UBound(arr, 2)
            y = UBound(arr)
        On Error GoTo 0

        Dim j As Long
        Dim i As Long
        If x >= 0 And y >= 0 Then
            For i = LBound(arr, 1) To UBound(arr, 1)
                For j = LBound(arr, 2) To UBound(arr, 2)
                    p = p + arr(i, j) / (r + 1) ^ k
                    k = k + 1
                Next j
            Next i
        ElseIf y >= 0 Then
            For j = LBound(arr) To UBound(arr)
                p = p + arr(j) / (r + 1) ^ k
                k = k + 1
            Next j
        Else
            p = p + arr / (r + 1) ^ k
            k = k + 1
        End If
    Next FlowsPart

    MyNpv = p

End Function

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM