如何在调用的函数中终止VBA Sub

时间:2019-07-09 07:06:03

标签: excel vba exit

如果发生错误,如何使VBA子从调用的函数中退出?

我尝试将Exit Sub语句放入相关函数中,但是每当我保存并重新打开文件时,VBA都会自动将其更改为Exit Function

例如,如何获取下面的代码

Sub foo()
    userNum = userNum()

    MsgBox(var)
End Sub

Function userNum() As Integer
    userNum = InputBox("Enter your positive number")

    If var < 0 Then
        MsgBox("Invalid: your number must be positive.")
        Exit Sub
    End If
End Function

不执行MsgBox(var)

1 个答案:

答案 0 :(得分:1)

  1. 声明变量。
  2. 我建议将Application.InputBoxType:=1一起使用,以接受数字作为输入。
  3. 将结果声明为Variant,以便您可以处理Cancel中的InputBox按钮。还可以使用它来决定是否要显示数字。

这是您要绑的东西吗? (未经测试

Option Explicit

Sub foo()
    Dim numb As Variant
    numb = userNum()

    If numb <> False Then MsgBox numb
End Sub

Function userNum() As Variant
    Dim Ret As Variant

    Ret = Application.InputBox(Prompt:="Enter you number", Type:=1)

    If Ret = False Then
        userNum = False
        Exit Function
    ElseIf Ret < 0 Then
        MsgBox ("Invalid: your number must be positive.")
        userNum = False
        Exit Function
    End If

    userNum = Ret
End Function
相关问题