如何在VBA上的函数子例程中添加错误消息

我真的是一个学习VBA的新生。 我很困惑如何添加一个函数子例程中的错误信息。

这是我的问题,当我完成识别一个function,我怎么能添加这样的错误信息:“请按递增的顺序input值”?

例如:如果我键入=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 

您可以testing不正确的顺序,或者直接在函数中进行无效的input,并返回,而不是使用error handling

  • 更改variables名称以避免错误和混淆与现有的function
  • 使用变体函数来保存结果或两个自定义错误消息之一
  • 你可以使用双打而不是单打

 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 

尝试这个

 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