基于组合框的VBA sql查询

时间:2015-08-10 18:50:05

标签: sql-server vba combobox ado

过去几天我一直在努力寻找并且遇到了许多例子,概述了我想要做的事情。但是,我似乎无法让这个工作。我有一个组合框,在表单初始化时从表中填充数据(公司名称)。然后,我想获取在组合框中选择的值并运行另一个查询以交叉引用同一个表中的id号。

    Private Sub CommandButton1_Click()



    Dim myCn As MyServer
    Set myCn = New MyServer

    Dim rs As ADODB.recordset
    Set rs = New ADODB.recordset

    Dim sqlStr As String
    Dim CompField As String

    'CompField = ComboBox1.Value



    sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = '" & ComboBox1.Text & "'"

    'sqlStr = "Select DISTINCT [company] FROM client;"

   ' sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Value & ";"

    'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = " & UserForm1.ComboBox1.Text & ";"

    'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE [company] = 'Company XYZ';"

    'sqlStr = "SELECT DISTINCT [acctno] FROM client WHERE company = " & CompField & ""



    rs.Open sqlStr, myCn.GetConnection, adLockOptimistic, adCmdText

     MsgBox sqlStr
    'MsgBox ComboBox1.Value
    'MsgBox rs(0)



    rs.Close
    myCn.Shutdown

    Set rs = Nothing
    Set myCn = Nothing


End Sub

目前,使用单引号括起来的组合框值,我得到了返回的整个sql字符串。如果我删除单引号,我会得到引用组合框值的一部分的语法错误。所有其他努力都导致运行时错误导致我无处可去。

我知道我的查询有效,因为我在SQL Studio中测试了它,如果我在此代码中硬编码文本值,我也会得到我正在寻找的帐户ID。不知道我在这里缺少什么。

1 个答案:

答案 0 :(得分:0)

好吧我明白了。我希望能够将MsgBox分配给SQL查询的变量并查看我的结果。但它不会那样工作。我不得不使用ADO GetString方法并分配另一个变量。哦,你是正确的逃避,我不得不添加分隔符来正确处理查询中的ComboBox值,最终看起来像这样

sqlStr = "SELECT DISTINCT [acct_no] FROM client WHERE [company] = " & Chr(39) & Me.ComboBox1.Value & Chr(39)

感谢您对此的帮助