3 种解决方案,每种都适用于您的情况。我会选择第一个或最后一个解决方案。取决于项目其余部分的设计:
1。功能
Function CheckEmptyComboboxValues() As Boolean
If AnythingOddHappens Then
Exit Function
End If
CheckEmptyComboboxValues = True
End Function
这个函数的结果只有True如果它跑到最后,只要你在它之前退出它就是False
Sub Example()
If Not CheckEmptyComboboxValues Then Exit Sub
'instead of
'Call CheckEmptyComboboxValues
End Sub
2。取消过程
Sub CheckEmptyComboboxValues(ByRef Cancel As Boolean)
If AnythingOddHappens Then
Cancel = True
Exit Sub
End If
End Sub
Sub Example()
Dim Cancel As Boolean
Call CheckEmptyComboboxValues(Cancel)
If Cancel Then Exit Sub
End Sub
这可以使用,但在这里我看不到任何优势,并且更喜欢上面的功能。如果您已经有一个带有返回值的函数并且想要一个额外的取消,或者如果您为一个事件编写代码,这个方法会很有用。
3。抛出错误
Sub CheckEmptyComboboxValues()
If AnythingOddHappens Then
Err.Raise vbObjectError + 513, "CheckEmptyComboboxValues", "Something odd happened"
Exit Sub
End If
End Sub
Sub Example()
On Error Goto ERR_HANDLER
Call CheckEmptyComboboxValues
Exit Sub
ERR_HANDLER:
MsgBox "check failed"
End Sub
如果您有多个可能引发错误的检查过程/功能,这可能是一个优势。与需要检查每个检查过程/功能的结果的第一个或第二个解决方案相比,此解决方案只需要一个错误处理程序,因此带有苗条的代码。
这还有一个好处是检查过程现在可以返回不同类型的错误,您的调用子可以使用这些错误为用户提供进一步的帮助。虽然前 2 个解决方案更像 “它没有通过检查”,但最后一个解决方案可以提供更详细的信息,例如 “它没有通过检查,因为 A/B/ C 发生” 取决于引发的错误。
Sub CheckEmptyComboboxValues()
If AnythingOddHappens Then
Err.Raise vbObjectError + 513, "CheckEmptyComboboxValues", "Something odd happened"
Exit Sub
End If
' more code here …
If AnythingDifferentOddHappens Then
Err.Raise vbObjectError + 514, "CheckEmptyComboboxValues", "Something different odd happened"
Exit Sub
End If
End Sub
现在您可以使用不同的错误编号向用户提供关于什么出了问题的更详细的信息,而不仅仅是某事出了问题。
Sub Example()
On Error Goto ERR_HANDLER
Call CheckEmptyComboboxValues
Exit Sub
ERR_HANDLER: 'possibility to give a more detailed information
Select Case Err.Number
Case vbObjectError + 513
MsgBox "check A failed"
Case vbObjectError + 514
MsgBox "check B failed"
Case Else
MsgBox "Undefined fail"
End Select
End Sub