0

我被困在从范围到变体的转换中。

对于percentageAbove 的功能,我想删除为0 的元素,然后使用percentageAboveHelper 中的输入。例如,如果

xInput 是 1, 2, 3, 4, 5, 6, 7, 8, 9, 10

y输入为 5, 0, 0, 2, 3, 4, 0, 4, 5, 0

我希望传递给 percentAboveHelper 的输入是

x输入:1、4、5、6、8、9

y输入:5、2、3、4、4、5

对于 percentAboveHelper 的功能,它本身就可以正常工作。但是,如果我通过percentageAbove 的变体,我会得到#value!

我试图检查哪一行导致#value!。所以,我在 percentAboveHelper 中写了 msgbox "1" 和 msgbox "2"。我看到如果我只使用 percentAboveHelper 本身,我可以看到消息 1 和 2。但是,如果我使用 percentAbove,我只能看到消息 1。

从这篇文章,在 VBA 函数中从范围切换到数组并返回我看到转换可以简单地通过变体 = range.value 完成。但它在我的情况下不起作用。有什么建议吗?

Function percentageAbove(above As Double, x As Double, xInput As Excel.Range, yInput As Excel.Range)
    Dim xRange As Excel.Range, yRange As Excel.Range
    For index = 1 To xInput.count
        If Not yInput.Item(index) = 0 Then
            If Not yRange Is Nothing Then
                Set xRange = Union(xRange, xInput.Item(index))
                Set yRange = Union(yRange, yInput.Item(index))
            Else
                Set xRange = xInput.Item(index)
                Set yRange = yInput.Item(index)
            End If
        End If
    Next index
    ' I do check the xRange and yRange. Both contain elements
    Dim xVariant As Variant, yVariant As Variant
    xVariant = xRange.Value
    yVariant = yRange.Value
    percentageAbove = percentageAboveHelper(above, x, xVariant, yVariant)
End Function

Function percentageAboveHelper(above As Double, x As Double, xVariant As Variant, yVariant As Variant)
    Dim n As Integer, df As Integer, meanOfX As Double, expectedY As Double, sste As Double, ssx As Double, se As Double
    n = Application.count(xVariant)
    df = n - 2
    meanOfX = Application.Average(xVariant)
    MsgBox "1"
    expectedY = Application.Forecast(x, yVariant, xVariant)
    MsgBox "2"
    sste = Application.StEyx(yVariant, xVariant)
    ssx = Application.DevSq(xVariant)
    se = sste * Sqr(1 / n + (x - meanOfX) ^ 2 / ssx)
    Dim tValue As Double, oneTailConf As Double
    tValue = (expectedY - above) / se
    oneTailConf = Application.TDist(Abs(tValue), df, 1)
    If tValue > 0 Then
        percentageAboveHelper = 1 - oneTailConf
    Else
        percentageAboveHelper = oneTailConf
    End If
End Function
4

0 回答 0