从用户定义的函数获取返回值时出错
我的用户定义的函数总是返回“公式中使用的值是错误的数据types”(我正在将单元格范围传递给函数)。 我search了很multithreading,我很确定我的代码应该工作:
Function SortAndEvaluate(ByRef Probs() As Variant, ByRef ResidualProbs() As Variant, ByRef Costs() As Variant) Dim Temp As Double Dim i As Integer Dim NoExcanges As Integer 'Exchange values in probs in descending order Do NoExchanges = True ' Loop through each element For i = 0 To UBound(Probs) - 1 'If element is greater than the last exchange, else do nothing If Probs(i) > Probs(i + 1) Then NoExchanges = False ' Exchange probability values Temp = Probs(i) Probs(i) = Probs(i + 1) Probs(i + 1) = Temp ' Exchange residual probability values Temp = ResidualProbs(i) ResidualProbs(i) = ResidualProbs(i + 1) ResidualProbs(i + 1) = Temp ' Exchange cost values Temp = Costs(i) Costs(i) = Costs(i + 1) Costs(i + 1) = Temp End If Next i Loop While Not (NoExchanges) Temp = 0 For i = 1 To UBound(Probs) If i = 1 Then Temp = Temp + Probs(i) * Costs(i) Else Temp = Temp + Probs(i) * ResidualProbs(i - 1) * Costs(i) End If Next i SortAndEvaluate = Temp End Function
任何人都可以给我任何反馈吗?
尝试类似
Option Explicit Function SortAndEvaluate(ByRef Probs As Range, ByRef ResidualProbs As Range, ByRef Costs As Range) Dim NumberOfProbs As Long Dim NumberOfProbsRows As Long Dim NumberOfProbsColumns As Long Dim RangeAddressProbs As String ' Dim for ResidualProbs and Costs ' ... NumberOfProbs = Probs.Cells.Count NumberOfProbsRows = Probs.Rows.Count NumberOfProbsColumns = Probs.Columns.Count RangeAddressProbs = Probs.Address ' also for ResidualProbs and Costs ' ... ' Might want some validation, eg If NumberOfProbsColumns <> 1 Then Exit Function If NumberOfResidualProbsColumns <> 1 Then Exit Function ' Get Values from range as an array Dim ValuesProbs As Variant Dim ValuesResidualProbs As Variant Dim ValuesCosts As Variant ValuesProbs = Probs ValuesResidualProbs = ResidualProbs ValuesCosts = Costs ' Do your logic stuff using the Values... arrays ' ... ' This example return value shows how to reference the Values... arrays (note you need to index the column too) SortAndEvaluate = ValuesProbs(NumberOfProbsRows, 1) End Function
您没有使用Option Explicit,而且在您的代码中,您的Dim NoExcanges As Integer
位置也存在印刷错误。
当你以后写NoExchanges = True
这隐式地Dim
sa新types的布尔引用NoExchanges
– NoExcanges
从不使用。
你也可能想要明确地说明函数的返回types:
Function SortAndEvaluate(ByRef Probs() As Variant, ByRef ResidualProbs() As Variant, ByRef Costs() As Variant) As Double
原因是Excel VBA不允许用户定义的函数来更改另一个单元格的值。 UDF唯一允许做的事情(有一些小例外)是将值返回给它所调用的单元格。
Probs(i) = Probs(i + 1)
函数内部是不允许的。
看到类似的问题
你可以用一个Sub做到这一点,但你必须通过单元格以另一种方式sorting(可能使用Selection
)。