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

时间:2017-02-19 23:32:23

标签: excel vba excel-vba

我真的是一个研究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

2 个答案:

答案 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