为文本框分配值

时间:2014-05-12 16:57:41

标签: sql function vba ms-access

我正在尝试将表字段的值分配给表单上的文本框,并且它一直给我错误...

Function getInjuryID(Socail As String)
  Dim dba As Database
  Dim rst As Recordset
  Dim SQL As String

  Set dba = CurrentDb

  SQL = "SELECT InjuryID,Employee_SSN FROM Injuries WHERE InjuryID IN(SELECT MAX(InjuryID) FROM Injuries GROUP BY Employee_SSN) AND Claim_StatusID = 'Open' AND Employee_SSN = " & Socail

  Set rst = dba.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)

  Set Me.Recordset = rst

  Set dba = Nothing
  Set rst = Nothing

End Function

呼...

Private Sub WcCaseYes_AfterUpdate()
  Me.InjuryID = getInjuryID(Me.SocialSecurityNumber.Value)

End Sub

它一直给我错误“你不能为这个对象赋值?

谢谢!

1 个答案:

答案 0 :(得分:0)

您编写的选择查询似乎是多余的。试试这个:

SELECT MAX(InjuryID) as maxInjuryID  FROM Injuries where Employee_SSN = SsnToLookUp and Claim_StatusID = 'Open'

您可以通过多种方式设置文本框的值

将控件源设置为类似

的表达式
=DMax("InjuryID","Injuries", "Employee_SSN = " & <SsnToLookUp> & " and Claim_StatusID = 'Open'")

或者您可以像打算一样打开记录集,并将字段的值设置为控件。

Function getInjuryID(Socail As String)
  Dim dba As DAO.Database
  Dim rst As DAO.Recordset
  Dim SQL As String

  Set dba = CurrentDb

  SQL = "SELECT MAX(InjuryID) as maxInjuryID FROM Injuries where Employee_SSN = " & Socail  & "and claim_StatusID = 'Open'"

  Set rst = dba.OpenRecordset(SQL, dbOpenDynaset, dbSeeChanges)

  if rst.recordcount>0 then
      getInjuryID = rst("maxInjuryID")
  end if
End Function

虽然最安全的方法是使用参数化查询(以防止sql注入)

Function getInjuryID()
    Dim rst As DAO.Recordset
    Dim qdef As New DAO.QueryDef
    Dim sql As String
    Dim db As DAO.Database
    Set db = CurrentDb


    On Error Resume Next
    Set qdef = db.QueryDefs("myq")
    If Err.Number = 3265 Then
        sql = "SELECT MAX(InjuryID) as maxInjuryID FROM Injuries where Employee_SSN = SocailToLookUp and claim_StatusID = 'Open'"
        db.CreateQueryDef "MyQ", sql
    End If
    On Error GoTo 0

    Set qdef = db.QueryDefs("MyQ")
    qdef.Parameters("SocailToLookUp") = Social
    Set rst = qdef.OpenRecordset

    If rst.RecordCount > 0 Then
        getInjuryID = rst("maxInjuryID")
    End If

End Function