如何在错误后停止执行代码?

How to stop code from executing after error?

我的表单允许用户通过各种控件进行过滤,包括字符串搜索框。一个单独的函数 CalculateSearchString 处理此搜索字段以进行过滤(关键字、精确短语等);在这个函数中,我使用错误处理来捕获由不正确的用户输入(即打乱标点符号)引起的错误。错误处理工作顺利,但如果搜索输入不正确,我希望代码完全停止

我想要的:

  1. 用户输入格式不正确的搜索字符串,点击过滤器
  2. 函数CalculateSearchFilter 抛出错误。消息框:“修复您的搜索词!”
  3. 代码完全停止,不应用过滤器

实际发生了什么:

  1. 用户输入格式不正确的搜索字符串,点击过滤器
  2. 函数CalculateSearchFilter 抛出错误。消息框:“修复您的搜索词!” Exit function
  3. 调用过程 cmdFilterOn 仍在运行,应用了不完整的过滤器(好像搜索框是空的)

问题:如何完全停止代码执行,不仅在函数中,而且在其调用过程中?函数在多个地方使用,所以将它与调用过程合并是不切实际的。

Private Sub cmdFilterOn()
    Dim strSearch As String
    strSearch = CalculateSearchFilter

    'do more stuff
End Sub

Private Function CalculateSearchFilter() As String
On Error GoTo ErrHandler
    'do stuff
    If 'user input is wrong, then raise a custom error:
        Err.Raise 50000
    End If

ExitHandler:
    Exit Function
ErrHandler:
    If Err.Number = 50000 Then msgbox "Fix your search terms!"
    Resume ExitHandler
End Sub

Private Sub cmdYetAnotherButton()
    'which also calls on CalculateSearchFilter
End Sub

将输入验证移至调用过程也不切实际,因为这会迫使我重复 CalculateSearchFilter() 中的大部分代码。

(当我写这篇文章时,我想到了另一个解决方案,即在函数错误处理程序中设置 CalculateSearchFilter = "an error occurred",并在调用过程中设置

If CalculateSearchFilter = "an error occurred" Then Exit Sub

...但是有更“官方”的答案吗?)

您可以尝试 return 布尔值

Option Explicit

Private Sub cmdFilterOn()
    Dim strSearch As String
    If CalculateSearchFilter(strSearch) Then

        'do more stuff
    
    End If
End Sub

Private Function CalculateSearchFilter(ByRef strSearch As String) As Boolean
On Error GoTo ErrHandler
    'do stuff
    If 'user input is wrong, then raise a custom error:
        Err.Raise 50000
    End If

    CalculateSearchFilter = True
    
ExitHandler:
    Exit Function
ErrHandler:
    If Err.Number = 50000 Then MsgBox "Fix your search terms!"
    CalculateSearchFilter = False
    Resume ExitHandler
End Function

Private Sub cmdYetAnotherButton()
    'which also calls on CalculateSearchFilter
End Sub

备选方案: 如评论中所述,如果您想返回一个字符串,那么我会 return 一个空字符串。我不建议 return 像 发生错误 之类的字符串

Option Explicit

Private Sub cmdFilterOn()
    Dim strSearch As String
    strSearch = CalculateSearchFilter
    If Len(strSearch) > 0 Then

        'do more stuff
    
    End If
End Sub

Private Function CalculateSearchFilter() As String
On Error GoTo ErrHandler
    'do stuff
    If 'user input is wrong, then raise a custom error:
        Err.Raise 50000
    End If

    
    
ExitHandler:
    Exit Function
ErrHandler:
    If Err.Number = 50000 Then MsgBox "Fix your search terms!"
    CalculateSearchFilter = vbNullString
    Resume ExitHandler
End Function

Private Sub cmdYetAnotherButton()
    'which also calls on CalculateSearchFilter
End Sub