我陷入了从范围到变体的转换。
对于percentageAbove的函数,我想删除0的元素,然后使用percentageAboveHelper中的输入。例如,如果
xInput为1,2,3,4,5,6,7,8,9,10
yInput是5,0,0,2,3,4,0,4,5,0
我希望传递给percentageAboveHelper的输入为
xInput:1,4,5,6,8,9
y输入:5,2,3,4,4,5
对于percentageAboveHelper的功能,它本身可以正常工作。但是,如果我从percentageAbove传递变体,我会得到#value!
我试图检查哪一行导致#value!。所以,我写了msgbox" 1"和msgbox" 2"在percentageAboveHelper中。我看到如果我只使用percentageAboveHelper本身,我可以看到消息1和2.但是,如果我使用percentageAbove,我只能看到消息1。
在这篇文章中,Switching from Range to Array and Back in a VBA Function我看到转换可以通过variant = 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