如何从Excel VBA用户窗体中显示SQL语法错误

时间:2015-08-17 04:21:15

标签: sql-server excel vba excel-vba odbc

我想请求一些帮助,这里有上下文:我使用的是连接到我的SQL Server和ODBC的Excel工作簿,因此用户可以使用它来进行一些查询一些宏+按钮。

他问我是否可以在Excel和SQL Server之间创建一个界面,就好像你正在使用DBMS,显示用户表单来键入查询以及是否出现一些语法错误,它会向你展示。)

这是我的问题:我已经成功创建了界面,但是我无法显示语法错误。它只显示以下消息:"运行时错误' 1004' SQL语法错误"。

如果您正在使用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

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

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

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