我真的是一个研究VBA的新生。我对如何在函数子例程中添加错误消息感到困惑。
这是我的问题,当我完成识别功能时,如何添加如下错误信息:“请按递增顺序输入值”?
例如:如果我输入=triangular(3,2,1)
,其中数字是递减顺序,我应该收到一条错误消息。
这是我的代码:
Public Function triangular(Minimum As Single, mostlikelyvalue As Single, maximum As Single) As Single
Dim uniform As Single
Dim d As Single
Randomize
Application.Volatile
d = (mostlikelyvalue - Minimum) / (maximum - Minimum)
uniform = Rnd
If uniform <= d Then
triangular = Minimum + (maximum - Minimum) * Sqr(d * uniform)
Else
triangular = Minimum + (maximum - Minimum) * (1 - Sqr((1 - d) * (1 - uniform)))
End If
End Function
答案 0 :(得分:2)
您可以直接在函数中测试错误的顺序或无效的条目,并返回该条目而不是使用错误处理
码
Public Function triangular(dbMinimum As Double, dbMostlikelyvalue As Double, dbMaximum As Double)
Dim uniform As Double
Dim d As Double
Dim dbCnt As Double
dbCnt = dbMinimum * dbMostlikelyvalue * dbMaximum
If dbCnt = 0 Then
triangular = "at least one value is zero"
Exit Function
End If
If dbMostlikelyvalue > dbMaximum Or dbMinimum > dbMostlikelyvalue Then
triangular = "values not sorted"
Exit Function
End If
Randomize
Application.Volatile
d = (dbMostlikelyvalue - dbMinimum) / (dbMaximum - dbMinimum)
uniform = Rnd
If uniform <= d Then
triangular = dbMinimum + (dbMaximum - dbMinimum) * Sqr(d * uniform)
Else
triangular = dbMinimum + (dbMaximum - dbMinimum) * (1 - Sqr((1 - d) * (1 - uniform)))
End If
End Function
答案 1 :(得分:1)
试试这个
Public Sub Sample
On Error Goto Err
'call your function here
'some more codes here
Exit Sub 'if all goes well code ends here
Err: 'Error handler
MsgBox Err.Description
End Sub