[英]VBA On Error Exit Calling Function
I have a simple excel function that connects to a db and retrieves some data and populates a worksheet. 我有一个简单的excel函数连接到数据库并检索一些数据并填充工作表。 The function calls another function to make the db connection and return the query results.
该函数调用另一个函数来建立数据库连接并返回查询结果。 How do I exit the calling function if there is an error connecting to the database?
如果连接到数据库时出错,如何退出调用函数? This is what my function looks like that connects to the DB.
这就是我的函数看起来连接到数据库的样子。 If there is an error connecting to the DB, the messagebox is displayed but then processing resumes in the calling function and then I get an ugly "END or DEBUG" message box...which I am trying to avoid.
如果连接到DB时出错,则显示消息框,但随后在调用函数中继续处理,然后我得到一个丑陋的“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
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
You may want to handle your errors in the calling sub though since errors "bubble up" to the caller. 您可能希望在调用子中处理错误,因为错误会“冒泡”到调用者。 This will cause your macro to debug even though you have an error handler in QueryDB.
即使在QueryDB中有错误处理程序,这也会导致宏进行调试。
Here is an example of how you can handle errors in called functions 以下是如何处理被调用函数中的错误的示例
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
Use " exit sub " command wherever necessary. 必要时使用“ exit sub ”命令。 as you did n't shared your subroutine/function, I cannot point out where it needs to be given.
因为你没有共享你的子程序/功能,我不能指出它需要给出的位置。 add " exit sub " according to your logic.
根据你的逻辑添加“ exit sub ”。
Regards, 问候,
Dominic 多米尼克
It can be done using Global level variable as below: 可以使用全局级变量完成,如下所示:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.