用户定义函数在不同选项卡上返回相同结果

时间:2019-12-15 17:34:35

标签: excel vba excel-formula

我有这段代码可以分析股票收益,我计划有10-20个标签,每个标签上都有不同的库存:

Function myStrategyReturn(sell As Double, buy As Double) As Double

Dim x As Double

Application.Volatile

changes = Range("H2:H263")

PreviousFlag = "Buy"

startingBalance = Range("P5").Value

newBal = Range("P5").Value

For i = UBound(changes) To 1 Step -1

x = changes(i, 1)
If PreviousFlag = "Sell" Then

    If x <= buy Then

        PreviousFlag = "Buy"

    Else

        newBal = newBal

    End If

ElseIf x <= buy Or i = UBound(changes) Then

    newBal = (newBal * (1 + x))
    PreviousFlag = "Buy"

ElseIf x < sell And x > buy Then 'our return is below the sell threshold, but above the buy

    newBal = (newBal * (1 + x))
    PreviousFlag = "Buy"

ElseIf x >= sell Then

    newBal = (newBal * (1 + x))
    PreviousFlag = "Sell"

End If

Next i

myStrategyReturn = ((newBal - startingBalance) / startingBalance)

End Function

我遇到的问题是每个选项卡当前都返回相同的结果。公式输入始终相同,但范围H2:H263不同。由于某种原因,该公式会不断返回我上次进行完整计算的选项卡的返回值。

2 个答案:

答案 0 :(得分:2)

类似以下代码行:

changes = Range("H2:H263")

将从 ActiveSheet 中选择数据,而不是从单元格中显示UDF的工作表中获取数据。

答案 1 :(得分:1)

加里(Gary)的解决方案行之有效,这是一个替代方案,它可以在公式中捕获您的输入,这比尝试在VBA中进行编码要好。

Function myStrategyReturn(sell As Double, buy As Double, Changes As Range, startingBalance As Range) As Double

Dim x As Double, i As Long, previousFlag As String


'may not need this.
Application.Volatile

previousFlag = "Buy"

Dim Newbal As Double

Newbal = startingBalance.Value

For i = UBound(Changes) To 1 Step -1

x = Changes(i, 1)
If previousFlag = "Sell" Then

    If x <= buy Then

        previousFlag = "Buy"

    Else

        Newbal = Newbal

    End If

ElseIf x <= buy Or i = UBound(Changes) Then

    Newbal = (Newbal * (1 + x))

    previousFlag = "Buy"

ElseIf x < sell And x > buy Then 'our return is below the sell threshold, but above the buy

    Newbal = (Newbal * (1 + x))

    previousFlag = "Buy"

ElseIf x >= sell Then

    Newbal = (Newbal * (1 + x))

    previousFlag = "Sell"

End If

Next i

myStrategyReturn = ((Newbal - startingBalance.Value2) / startingBalance.Value2)

End Function