如何从被调用函数中终止 VBA Sub

How to Terminate VBA Sub from within called Function

如果发生错误,如何让 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. 声明变量。
  2. 我建议使用 Application.InputBoxType:=1 来接受数字作为输入。
  3. 将结果声明为 Variant 以便您可以处理 InputBox 中的 Cancel 按钮。也用它来决定是否要显示号码。

这是你绑定的吗? (未测试)

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