【问题标题】:VBA On Error Exit Calling FunctionVBA 错误退出调用函数
【发布时间】:2023-03-15 19:01:01
【问题描述】:
我有一个简单的 Excel 函数,它连接到数据库并检索一些数据并填充工作表。该函数调用另一个函数来建立数据库连接并返回查询结果。如果连接数据库出错,如何退出调用函数?这就是我的函数连接到数据库的样子。如果连接到数据库时出错,则会显示消息框,但随后会在调用函数中继续处理,然后我会收到一个丑陋的“END 或 DEBUG”消息框...我正在努力避免。
Public Function QueryDB(sQuery As String)
On Error GoTo ErrorHandler
... Connect to database and get data
ErrorHandler:
... Display a messagebox telling the user there is an error
'Resume Next
Exit Function
End Function
【问题讨论】:
标签:
vba
excel
error-handling
【解决方案1】:
可以使用如下全局级别变量来完成:
Public dbError as Integer
Function ConnectToDb as Integer
On Error GoTo err_Connection
'Asume connection to DB failure
err_Connection:
MsgBox "Connection failed to database !! ", vbOKOnly + vbExclamation
dbError = -500 'Any number
Exit Function
End Function
Sub MainSub
'Call function
ConnectToDb
If dbError = -500 Then
Exit Sub
End If
End Sub
【解决方案2】:
Public Function QueryDB(sQuery As String)
On Error GoTo ErrorHandler
'... Connect to database and get data
' Exit function before the error handler so
' it doesn't get processed every run
Exit Function
ErrorHandler:
' ... Display a messagebox telling the user there is an error
MsgBox "Oops! An error occurred."
End Function
您可能希望在调用子程序中处理您的错误,因为错误会“冒泡”给调用者。即使您在 QueryDB 中有错误处理程序,这也会导致您的宏进行调试。
这是一个如何处理被调用函数中的错误的示例
Sub Main()
On Error GoTo DBERROR
QueryDB ("Query String")
On Error GoTo 0
Exit Sub
DBERROR:
MsgBox "Oops! Error " & Err.Number & " occurred in " & Err.Source & ".", _
Title:="Error " & Err.Number
End Sub
Public Function QueryDB(sQuery As String)
Err.Raise 5000, "QueryDB", "Error connecting to DB"
End Function
【解决方案3】:
在必要时使用“exit sub”命令。由于您没有共享您的子程序/功能,因此我无法指出需要在哪里提供。根据您的逻辑添加“exit sub”。
问候,
多米尼克