如何从 Excel VBA 用户表单显示 SQL 语法错误

How to display SQL Syntax error from a Excel VBA Userform

我想寻求一些帮助,这是上下文:我正在使用一个 Excel 工作簿,该工作簿通过 ODBC 连接到我的 SQL 服务器,因此用户可以使用它来使用一些宏 + 按钮进行一些查询。

他问我是否可以在 Excel 和 SQL 服务器之间创建一个接口,比如如果你使用的是 DBMS,显示一个用户表单来输入查询,如果你得到一些语法错误,它会显示给你)。

我的问题是:我已经成功创建了界面,但是我无法显示语法错误。只显示消息:"Run Time Error '1004' SQL Syntax Error".

是否可以像使用 DBMS 一样显示准确的消息?


为了更容易理解,这是我的代码:

Function Query(SQL As String)

On Error GoTo Err_handler

    With ActiveSheet.QueryTables.Add(Connection:= _
        "ODBC;DSN=mydb;Description=test;UID=test;PWD=test;APP=Microsoft Office 2003;WSID=test123" _
        , Destination:=Range("A1"))
        .CommandText = (SQL)
        .Name = "test"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .BackgroundQuery = True
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .PreserveColumnInfo = True
        .Refresh BackgroundQuery:=False
    End With

    Exit Function

Err_handler:
    MsgBox Err.Number & " - " & Err.Description

End Function

提前致谢!

您需要使用类似 ActiveX Data Objects 库 (ADODB) 的东西,以便您可以获得特定的连接信息。因此,当您 运行 代码时,SQL 将在 ADO 对象上引发错误,但随后 Err 对象将包含 SQL-特定的错误信息,从数据库。

您需要在 VBA 项目中向 ActiveX Data Objects 添加一个 Reference。完成后,试试这个:-

Function MyQuery(SQL As String)

  Dim cn As ADODB.Connection
  Dim cmd As ADODB.Command
  Dim rs As ADODB.Recordset

  On Error GoTo Err_handler

  'DB Connection Object
  Set cn = New ADODB.Connection
  cn.Open "DSN=mydb;Description=test;UID=test;PWD=test;APP=Microsoft Office 2003;WSID=test123"

  'SQL Command Object
  Set cmd = New ADODB.Command
  cmd.ActiveConnection = cn
  cmd.CommandType = adCmdText
  cmd.CommandText = SQL

  'Recordset Object to contain results
  Set rs = cmd.Execute

  With ActiveSheet.QueryTables.Add(Connection:=rs, Destination:=Range("A1"))
    .Name = "test"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .Refresh BackgroundQuery:=False
  End With

MyQueryx:

  'Clean up - close connections and destroy objects
  If Not rs Is Nothing Then
    If rs.State = ADODB.adStateOpen Then
      rs.Close
    End If
    Set rs = Nothing
  End If

  If Not cmd Is Nothing Then
    Set cmd.ActiveConnection = Nothing
    Set cmd = Nothing
  End If

  If Not cn Is Nothing Then
    If cn.State = ADODB.adStateOpen Then
      cn.Close
    End If
    Set cn = Nothing
  End If

  Exit Function

Err_handler:
  MsgBox Err.Number & " - " & Err.Description
  'Goto to the function exit to clean up
  GoTo MyQueryx

End Function