在Access中创建搜索框

时间:2016-05-22 15:15:52

标签: vba ms-access access-vba

我使用Access数据库来管理员工信息。我想创建一个搜索框,这样当我输入员工ID时,其余信息可以自动填写。

我创建了一个函数来尝试获取每个列的值,并在单击按钮时分配它,但它不起作用。

以下是代码:

Public Function GetEmployeeName() As ADODB.Recordset
    Dim rst As ADODB.Recordset
    Set GetEmployeeName = CurrentProject.Connection.Execute("select EmployeeName From EInfor where EmployeeID = " & txtEID.Value)
End Function

Private Sub btnSearch_Click()
    txtEmployeeName = GetEmployeeName()
End Sub

3 个答案:

答案 0 :(得分:1)

我觉得GetEmployeeName()应该返回与给定EmployeeName匹配的EmployeeID。在这种情况下,您不需要RecordsetDLookup表达式可以为您提供所需的内容。

Public Function GetEmployeeName(ByVal pEID As Long) As Variant
    GetEmployeeName = DLookup("EmployeeName", "EInfor", "EmployeeID=" & pEID)
End Function

该函数希望您提供目标EmployeeID作为参数,因此它不会硬连接到某个特定表单上的控件的值。

如果未找到匹配的EmployeeName,则该函数返回Null。在命令按钮的点击事件中,您可以使用Nz()替换其他内容为空。

Private Sub btnSearch_Click()
    Me!txtEmployeeName.Value = Nz(GetEmployeeName(Me!txtEID.Value), "unknown")
End Sub

答案 1 :(得分:0)

您尝试将txtEmployeeNameValue属性)的默认属性设置为GetEmployeeName(),返回ADODB.Recordset,其默认属性为Fields },这是一个集合。

这不太可行。

请改为尝试:

txtEmployeeName = GetEmployeeName().Fields(0)

如果要更新多个文本框,则应考虑仅使用一个SELECT语句一次性检索所有需要的值:

"select * From EInfor where EmployeeID = " & CLng(txtEID.Value)

然后你可以像这样更新文本框:

txtEmployeeName    = rst.Fields("EmployeeName")
txtEmployeeBoss    = rst.Fields("EmployeeBoss")
txtEmployeeAddress = rst.Fields("EmployeeAddress")
txtEmployeeSalary  = rst.Fields("EmployeeSalary")

请注意以下更改:

答案 2 :(得分:0)

您可以创建一个ComboBox,在您键入时过滤记录集。当您搜索与您要查找的记录类似但可能不完全匹配的记录时,这非常有用!

按Alt + F11并右键单击之前创建的表单。粘贴在下面的脚本中。

[![Option Compare Database

Private Sub ComboSelect_Change()

    '  You need to use String delimiters if you want to use a Text Field like:
    '  Me.Filter "\[ATextFieldInRecordSource\] = """ & Me.FilterComboBox & """"

    '  For a Numeric Field, use something like this:
    '  Me.Filter "\[ANumericFieldInRecordSource\] = " & Me.FilterComboBox
    '  Me.FilterOn = True

    Me.\[Customer_Query subform1\].Form.Filter = "\[Company_Name\] Like '*" &
                     Replace(Me.ComboSelect.Text, "'", "''") & "*'"
    Me.\[Customer_Query subform1\].Form.FilterOn = True

End Sub][1]][1]



Notice a few things:
•   The subform is named Customer_Query subform1’
•   The combobox is named ComboSelect’
•   Finally, the ‘like clause’ is used in combination with the wildcard character.
•   Like '*" & Replace(Me.ComboSelect.Text, "'", "''") & "*'"

在组合框中键入文本时,会动态重新查询子表单中的结果。