尝试使用SQL查询结果填充Excel Userform文本框

时间:2018-06-18 23:21:56

标签: sql excel vba excel-vba

我正在尝试在用户输入记录号时使用SQL填充Userform。

Userform

Private Sub Enter_Click()
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sSQL As String
    Dim strConn As String
    Set rs = New ADODB.Recordset
    sSQL = "SELECT ACCOUNT NAME,ACCOUNT NUMBER"
    sSQL = sSQL & "FROM SQL DATABASE"
    sSQL = sSQL & "WHERE RECORD_NBR = Record.txt"
    Set cn = New ADODB.Connection
    rs.Open sSQL, cn
    AcctName.Text = rs.Fields!ACCOUNT NAME
    AcctNum.Text = rs.Fields!ACCOUNT NUMBER
    strConn = "Data Source=database;UID=1234;PWD=Password1;Database=SQL DATABASE"
    cn.Open strConn
    cn.Close
    Set cn = Nothing
End Sub

当我运行下面的代码时,我收到错误3907.新的,不清楚我做错了什么...请指教。

Error 3907

2 个答案:

答案 0 :(得分:0)

在使用连接之前,必须先打开它。要解决此问题,只需调用cn对象的Open方法 - 但您需要一个连接字符串来执行此操作。

要拥有一个健壮的应用程序,最好包含一个错误处理程序来处理数据库连接失败或查询失败的情况。此外,您应该考虑确保返回的记录数量符合您的预期,并处理返回的内容不符合您的期望或要求的情况。

在您的代码上...您有一个名为strConn的字符串,它看起来像一个连接字符串,但您的代码有点混乱。试试这个:

Private Sub Enter_Click()
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sSQL As String
    Dim strConn As String

    sSQL = "SELECT ACCOUNT NAME,ACCOUNT NUMBER"
    sSQL = sSQL & "FROM SQL DATABASE"
    sSQL = sSQL & "WHERE RECORD_NBR = Record.txt"

    strConn = "Data Source=database;UID=1234;PWD=Password1;Database=SQL DATABASE"
    Set cn = New ADODB.Connection

    cn.Open strConn
    rs.Open sSql, cn

    ' you may want code here to ensure that only one record was returned
    ' or perhaps you want to process multiple records

    AcctName.Text = rs.Fields!ACCOUNT NAME
    AcctNum.Text = rs.Fields!ACCOUNT NUMBER

    'Close the recordset
    rs.Close
    Set rs = Nothing

    'Close the connection
    cn.Close
    Set cn = Nothing
End Sub

答案 1 :(得分:0)

有两个错误。第一个是必须首先调用连接,然后必须加载记录集,并且sql语法本身有问题。

Private Sub Enter_Click()
    Dim cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sSQL As String
    Dim strConn As String
    Set rs = New ADODB.Recordset
    sSQL = "SELECT ACCOUNT NAME,ACCOUNT NUMBER " '<~~ Space is required.
    sSQL = sSQL & "FROM SQL DATABASE " '<~~ Space is required.
    sSQL = sSQL & "WHERE RECORD_NBR ='" & Record.txt & "' " '<~~Record.txt is variable
    Set cn = New ADODB.Connection

    strConn = "Data Source=database;UID=1234;PWD=Password1;Database=SQL DATABASE"
    cn.Open strConn
    rs.Open sSQL, cn
    AcctName.Text = rs.Fields!ACCOUNT NAME
    AcctNum.Text = rs.Fields!ACCOUNT NUMBER
    strConn = "Data Source=database;UID=1234;PWD=Password1;Database=SQL DATABASE"
    cn.Open strConn
    cn.Close
    Set cn = Nothing
End Sub