在SQL表中查找特定数据

时间:2013-10-21 09:41:17

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

我希望有人可以帮助我,我是SQL新手,这让我感到困惑。 我想通过inputbox在mySQL表中找到一个特定/匹配的数据,这段代码只能查找第一行中的数据而不能识别我数据库行中的第二个和其余数据。

这是我的代码..

Dim rs As New ADODB.Recordset
myConn
Dim holdstr As String
holdstr = InputBox("Enter Number")
rs.Open "SELECT * FROM lemployees ", conn
Do Until rs.EOF

If holdstr = "" Then
conn.Close
Exit Sub
End If

If holdstr = rs!ENumber Then
MsgBox "Record found!", vbInformation, "Message"

UserForm2.lblnum.Caption = rs!ENumber
UserForm2.TextBox2.Text = rs!ELName
UserForm2.TextBox3.Text = rs!EFName
UserForm2.TextBox4.Text = rs!EMName
UserForm2.boxPos = rs!EDepartment
UserForm2.TextBox6.Text = rs!EAge
UserForm2.TextBox7.Text = rs!EHourlyPaid
UserForm2.TextBox8.Text = rs!ECitizen

conn.Close
Exit Sub
Else
MsgBox "Record not found", vbInformation, "Message"
Exit Sub
End If
Loop

谢谢!

1 个答案:

答案 0 :(得分:0)

退出循环内的Sub。即使找不到您要找的物品。

尝试

Dim rs As New ADODB.Recordset
myConn
Dim holdstr As String
holdstr = InputBox("Enter Number")

If holdstr = "" Then
  Exit Sub
End If

rs.Open "SELECT * FROM lemployees ", conn
Do Until rs.EOF
  If holdstr = rs!ENumber Then
    MsgBox "Record found!", vbInformation, "Message"

    UserForm2.lblnum.Caption = rs!ENumber
    UserForm2.TextBox2.Text = rs!ELName
    UserForm2.TextBox3.Text = rs!EFName
    UserForm2.TextBox4.Text = rs!EMName
    UserForm2.boxPos = rs!EDepartment
    UserForm2.TextBox6.Text = rs!EAge
    UserForm2.TextBox7.Text = rs!EHourlyPaid
    UserForm2.TextBox8.Text = rs!ECitizen

    conn.Close
    Exit Sub
    End If
  Loop
MsgBox "Record not found", vbInformation, "Message"
conn.Close
Exit Sub