选择时搜索功能运行时错误424

时间:2011-04-16 14:55:12

标签: ms-access vba access-vba

我的要求:使用VB表格和3个文本框搜索数据库中的数据。

1 TextBox,我将给输入(UserName)
1个位置的文本框
1个用于显示输出的TextBox

我的代码是

Private Sub CommandButton3_Click()

Dim Cn As ADODB.Connection '* Connection String

Dim oCm As ADODB.Command '* Command Object

Dim sName As String
Dim rs As ADODB.Recordset
Dim uname As String
Set Cn = New ADODB.Connection

Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
Cn.ConnectionTimeout = 40
Cn.Open
Set oCm = New ADODB.Command
oCm.ActiveConnection = Cn

‘Record Set
Set rs = New ADODB.Recordset

‘Select Operation
rs.Open "SampleTable", Cn, adOpenKeyset, adLockPessimistic, adCmdTable

uname = rs("UserName")

rs.Open "Select * from SampleTable where uname = '" & text1.Text & "'", ActiveConnection, adOpenForwardOnly, adLockReadOnly, adCmdText

**'Display the Output in TextBox3**
TextBox3.Text = rs("UserName") + rs("Location")

rs.Close
Cn.Close
End Sub

我可以理解没有发生数据填充,因此在Select语句中获取RunTime错误424。如何检索给定的相应输入的数据?

1 个答案:

答案 0 :(得分:0)

  1. 你不需要打开桌子;在搜索之前rs.Open "SampleTable"
  2. 不确定这是为了什么; uname = rs("UserName")
  3. 你应该跑; rs.Open "Select * ...(在同一个RS上运行.Open而不关闭第一个可能是导致错误的原因)
  4. 你应该逃避你的意见; replace$(text1.Text, "'", "''")
  5. 您应该在rs.EOF
  6. 之后检查.open
  7. 使用&而不是+来连接字符串
  8. 更新

    sub xxx
    Dim Cn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim sName As String
    
    Set Cn = New ADODB.Connection
    Cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=d:\test2.accdb;Persist Security Info=False"
    Cn.ConnectionTimeout = 40
    Cn.Open
    
    Set rs = New ADODB.Recordset
    
    sName = replace$(text1.Text, "'", "''")
    rs.Open "Select * from SampleTable where UserName = '" & sName & "'", Cn, adOpenForwardOnly, adLockReadOnly, adCmdText
    
    if (rs.eof) then
        msgbox "no match"
    else
        TextBox3.Text = rs("UserName") & " " & rs("Location")
        rs.Close
    end if
    
    set rs = nothing
    Cn.Close
    set cn = nothing
    end sub