即使表中包含记录,我的查询也不会返回任何值。我正在尝试根据输入的名称检索一个有效的ID。我不断收到消息"没有员工身份"。就Access VBA而言,我是一个新学习者。我已经使用Access表和其他表没有问题。我确实验证了表单字段具有正确的值并且正在变量 strEmpName
中捕获 Set cnn1 = New ADODB.Connection
mydb = "C:\accesssamp\Documents\Tasks.accdb"
strCnn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & mydb
cnn1.Open strCnn
'This statement added here just to indicate that I am getting the value
strEmpName = cboEmployeeName.Text ' Getting employee name from form field
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandText = "SELECT [EmployeeId] FROM [Employees] " & _
"WHERE [EmployeeName] = [strEmpName]"
.CommandType = adCmdUnknown
.Parameters.Append cmd.CreateParameter( _
"[strEmpName]", adChar, adParamInput, 50)
.Parameters("[strEmpName]") = strEmpName
End With
' Execute the Query and return the employeeId
Set rstEmp = cmd.Execute
If rstEmp.RecordCount < 1 Then
MsgBox "No Employee Id"
Else
MsgBox rstEmp(0).Value
End If
答案 0 :(得分:2)
您的样本有多个问题。我不确定这是否正是你想要的,但它在我的系统上没有错误。
With cmd
'.ActiveConnection = CurrentProject.Connection
.ActiveConnection = cnn1
.CommandText = "SELECT [EmployeeId] FROM [Employees] " & _
"WHERE [EmployeeName] = [strEmpName]"
.CommandType = adCmdUnknown ' or adCmdText; either works
.Parameters.Append cmd.CreateParameter( _
"strEmpName", adVarChar, adParamInput, 255, strEmpName)
End With
' Execute the Query and return the employeeId
Set rstEmp = cmd.Execute
'If rstEmp.RecordCount < 1 Then
If rstEmp.BOF And rstEmp.EOF Then
MsgBox "No Employee Id"
Else
MsgBox rstEmp(0).value
End If
注意:
CurrentProject.Connection
。CreateParameter
提供兼容的数据类型。对于文本参数,请为其最大长度提供值。最后包括参数的值。rstEmp.RecordCount
返回-1,小于1,因此即使记录集不为空,您的代码也会显示“No Employee Id”。而不是检查RecordCount
,检查记录集是否为空。