【问题标题】:vba to populate a textbox from SQL queries when combobox is change itvba 在组合框更改时从 SQL 查询填充文本框
【发布时间】:2013-10-07 15:31:44
【问题描述】:

我有一个用户表单,在 EXCEL 中有一个文本框和一个组合框。 此用户表单连接到一个小型数据库(一个有 2 列的表) 组合框填充了来自数据库表第一列的值 我喜欢组合框将文本框更改为自动填充第二列中的对应值。 我有以下代码,但它不工作: 请问,有人可以帮帮我吗?

Sub PopulateTB()

    Dim rs As Recordset
    Dim db As database
    Dim SQL As String

    Set db = OpenDatabase(ThisWorkbook.Path & "\materiale.mdb")

    SQL = "SELECT values_col2 FROM table_db WHERE values_col1 = " & UserForm1.ComboBox1.Value & ";"
    Set rs = db.OpenRecordset(sql)


 Do Until rs.EOF = True
    UserForm1.TextBox1.Value = rs.Fields(SQL)
    rs.MoveNext
 Loop

   rs.Close
    Set db = Nothing
    Set rs = Nothing

End Sub

谢谢!

【问题讨论】:

  • 它有什么作用?你得到一个错误还是什么都不做?你为什么要通过 rs 循环但将值覆盖到同一个文本框中?
  • but it is not working 这不能很好地描述您的问题。具体是什么不起作用,您希望看到什么,实际发生了什么?
  • 另外,您似乎只能获得文本框中的最后一个值,因为您每次都在覆盖它,这可能是您的问题(我不确定)
  • 对不起,我在 Set rs = db.OpenRecordset(SQL, dbReadOnly) 上遇到错误 3061(参数太少。预期为 1)。 @enderland,正确,我必须取出循环。

标签: sql excel vba combobox


【解决方案1】:

我是这样推的,没关系

Sub PopulateTB(ByRef ctl As Control, ByVal strTable As String, ByVal strField As String, Optional ByVal strCriteria As String)

    Dim strSQL As String
    Dim strSQLcount As String
    Dim rs As Recordset
    Dim db As Database
    Dim rsCount As Recordset, totalCol As Long
    Dim varRecords As Variant

    Set db = OpenDatabase(ThisWorkbook.Path & "\materiale.mdb")

    strSQLcount = ""
    strSQLcount = strSQLcount & " " & "SELECT COUNT(*) AS Total FROM " & "[" & strTable & "]"
    Set rsCount = db.OpenRecordset(strSQLcount)
    totalCol = rsCount!Total
    rsCount.Close
    Set rsCount = Nothing



    strSQL = ""
    strSQL = strSQL & " " & "SELECT" & "[" & strField & "]"
    strSQL = strSQL & " " & "FROM " & "[" & strTable & "]"

    Set rs = db.OpenRecordset(strSQL)



    varRecords = rs.GetRows(totalCol)
    ctl.Value = varRecords(0, Me.ComboBox1.ListIndex)

    rs.Close
    db.Close
    Set db = Nothing
    Set rs = Nothing


End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多