带变量的VBA访问

时间:2018-09-18 01:29:35

标签: ms-access access-vba

我的代码到底有什么问题,我想使用员工姓名和其相应ID上的Pin来更新表,但其他员工可以访问任何Pin,请帮帮我!

Dim CanteenPOS As DAO.Database
Dim tblEmployee As DAO.Recordset

Set CanteenPOS = CurrentDb

Dim ID As Integer

If IsNull(Me.txtName) Or IsNull(Me.txtPin) Then
    MsgBox "First! Please enter your EmployeeID before PinID", vbInformation
    Me.txtName.SetFocus
Else
    If (IsNull(DLookup("EmployeeID", "tblEmployeeID", "EmployeeID = '" & Me.txtName & "'"))) Or _
       (IsNull(DLookup("PinID", "tblEmployeeID", " PinID = '" & Me.txtPin & "'"))) Then 
        MsgBox "Invalid EmployeeID or PinID!"
    Else
        Me.txtUsername = DLookup("[EmployeeID]", "tblEmployeeID", "[EmployeeID] = '" & Me.txtName.Value & "'")
        Me.txtPin = DLookup("[PinID]", "tblEmployeeID", " [EmployeeID] = '" & Me.txtName.Value & "'")

        MsgBox ("Your transaction is completed!")
        Set tblEmployee = CanteenPOS.OpenRecordset("tblEmployee")
        tblEmployee.AddNew
        tblEmployee("EmployeeName").Value = Me.txtName
        tblEmployee("OrderName").Value = Me.txtOrderType
        tblEmployee("Price").Value = Me.txtprice
        tblEmployee("Datetime").Value = lblDate.Caption
        tblEmployee("AddOn").Value = Me.txtAdd
        tblEmployee.Update
    End If
End If

1 个答案:

答案 0 :(得分:1)

我认为问题出在第二个“ If”中的“ Or”之后:

If (IsNull(DLookup("EmployeeID", "tblEmployeeID", "EmployeeID = '" & Me.txtName & "'"))) Or _
   (IsNull(DLookup("PinID", "tblEmployeeID", " PinID = '" & Me.txtPin & "'"))) Then 
    MsgBox "Invalid EmployeeID or PinID!"

您正在检查EmployeeID和PinID都在数据库中,但您没有在检查它们是否在SAME记录中!只要SOMEBODY拥有图钉,测试就会通过!

通过在随后的Else中查找EmployeeID,与在检索到的记录中找到PinID的方式进行比较。

只需使用EmployeeID查找记录,然后找到与该EmployeeID一起使用的PinID。然后将找到的PinID与用户输入的PinID进行比较,以确保它们匹配,然后再保存新数据。

顺便说一句,DLookup并不是获取此信息的最有效方法。与SQL(或保存的查询)一起使用的Execute命令可以在您查找EmployeeID时获得PinID,而无需执行第二次DLookup。 (如果不确定如何编写SQL,请创建常规的Access查询,然后查看SQL视图。这将向您显示所需的内容。)

(C。Perkins关于安全性的评论有一些优点,但是如果您只是想让诚实的人避免犯诚实的错误-例如用一个数字迷惑其EmployeeID-那么请确保EmployeeID和PinID匹配可能足以您的目的。他们可能将EmployeeID和PinID保持在一起,以便其他员工也可以看到它们;-)