如何通过 Excel VBA 捕获 SQL 错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27824035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 05:44:23  来源:igfitidea点击:

How to Catch SQL Error through Excel VBA

sqlvbaexcel-vbaexcel

提问by jaysoncopes

I have a program that is going through the subfolders of a folder and running a stored SQL command on each. I am in the process of writing another module that will automatically check the files before being inputted, but I don't like having my company's test data hinging on a program without any way to know if something errored out. Here is the code I currently have:

我有一个程序,它遍历文件夹的子文件夹并在每个子文件夹上运行存储的 SQL 命令。我正在编写另一个模块,该模块将在输入之前自动检查文件,但我不喜欢让我公司的测试数据挂在程序上,而无法知道是否有错误。这是我目前拥有的代码:

Sub openConnection()

Set varConnection = New ADODB.Connection
Set varCommand = New ADODB.Command

varConnection.ConnectionString = "PROVIDER=SQLOLEDB;DATA SOURCE=192.168.1.186,1433;INITIAL CATALOG=Test1; INTEGRATED SECURITY=sspi;"
varConnection.Open

varCommand.CommandText = "importFile"
varCommand.CommandType = adCmdStoredProc
varCommand.ActiveConnection = varConnection

Set varParameter = varCommand.CreateParameter("filePath", adChar, adParamInput, Len(varFolderPath), varFolderPath)
varCommand.Parameters.Append varParameter

varCommand.Execute

varConnection.Close

End Sub

On occasion, the command will error out, causing the data to not be uploaded. How can I catch these SQL errorsthrough Excel VBA in order to handle them appropriately without it being treated as though it had gone through like a normal file?

有时,命令会出错,导致数据无法上传。我怎样才能通过 Excel VBA捕获这些SQL 错误,以便适当地处理它们,而不会像处理普通文件一样处理它们?

Note: I don't mind rewriting code- this is all still in alpha.

注意:我不介意重写代码——这一切仍处于 alpha 阶段。

回答by Will Marcouiller

I guess this might be what you are looking for...

我想这可能是你正在寻找的......

MS Access VBA trapping SQL Server Connection Error

MS Access VBA 捕获 SQL Server 连接错误

Sub OpenConnection()
    On Error GoTo ErrorHandler

    // Do your stuff here...

    ErrorHandler:
    Debug.Print Err.Number & " " & Err.Description
    ' Or else you could log the error in a file, or even display a message box, whatever...'
End Sub

From the answer provided by fionnualato the above-linked question.

fionnuala提供的答案到上述链接的问题。