2011-10-10 20 views
3

在Access 2007中,我正在搜索某個表以找到某個ID。 ID地址由用戶IDTxt在文本框中給出。
我得到錯誤80040e10沒有值的一個或多個參數。正在搜索某個表以找到某個ID:錯誤80040e10對於一個或多個參數沒有值

Private Sub Search_Click() 

'here a new part I'm not sure about... 
Dim cn As ADODB.Connection 
Dim rsQ As ADODB.Recordset 

Set cn = CurrentProject.Connection 
Set rsQ = New ADODB.Recordset 

Dim strSQL As String 

Dim ID_number As Integer 
Dim blnExists As Boolean 
blnExists = False 
ID_number = IDTxt.Value 

strSQL = "SELECT * FROM Table1 WHERE ID = ID_number;" 
rsQ.Open strSQL, cn, adOpenStatic 

If rsQ.RecordCount <> 0 Then 
    ' Found it 
    blnExists = True 
    MsgBox "found" 
Else 
    MsgBox "not found" 
End If 

End Sub 
+2

@@ Aya Abdelsalam:請不要忘記註冊並接受幫助您的答案。 –

+0

@@ Aya Abdelsalam:如果答案對您有幫助,請接受其中一項。 –

回答

2

你傳遞一個字符串無取代的價值;

strSQL = "SELECT * FROM Table1 WHERE ID = ID_number;" 

需要是

strSQL = "SELECT * FROM Table1 WHERE ID = " & ID_number 

作爲ID_number是僅在VBA的可變字符串的上下文。

(上ID_number因此在無限制的文本框的文本可能會錯誤您還沒有進行類型檢查,併爲字符串參數是注入漏洞)

還要注意的是RecordCount可以返回-1取決於光標位置/類型。

+0

非常感謝 –

3

這應該是:

rSQL = "SELECT * FROM Table1 WHERE ID = " & ID_number 

[注:這將是更好的做法是使用一個參數化查詢,以防止SQL注入]

+0

非常感謝你 –

2

建議:使用Command對象提供參數值例如

Dim cn As ADODB.Connection 
Dim rsQ As ADODB.Recordset 

Set cn = .ActiveConnection 

Set rsQ = New ADODB.Recordset 

Dim strSQL As String 

Dim ID_number As Integer 
Dim blnExists As Boolean 
blnExists = False 
ID_number = IDTxt.Value 

strSQL = "SELECT * FROM Table1 WHERE ID = ID_number;" 

Dim cmd As ADODB.Command 
Set cmd = New ADODB.Command 
With cmd 
    Set .ActiveConnection = cn 
    .NamedParameters = True 
    .CommandType = adCmdText 
    .CommandText = strSQL 
    .Parameters.Append .CreateParameter("ID_number", adInteger, , , ID_number) 
    Set rsQ = .Execute 
End With 

If rsQ.RecordCount <> 0 Then 
    ' Found it 
    blnExists = True 
    MsgBox "found" 
Else 
    MsgBox "not found" 
End If 
相關問題