Domanda

I am writing a vba code that loops through records and if record equals environment username then display its offset records of found username within a form showing in labels.

So far I have come across a brick wall, trying to get the values that belong to the matching username.

Table

Access Form

    Dim rs As DAO.Recordset    
    Set rs = CurrentDb.OpenRecordset("SELECT * FROM agentKPI")

    'Check to see if the recordset actually contains rows
    If Not (rs.EOF And rs.BOF) Then
        rs.MoveFirst 'Unnecessary in this case, but still a good habit
        Do Until rs.EOF = True
            'Perform an edit
         rs.Edit
         rs("staffName") = Environ$("username")

            Form!agentKPI!label10.Caption
            Form!agentKPI!label14.Caption
            Form!agentKPI!label23.Caption
            Form!agentKPI!label26.Caption

            'rs!kpi1 = True
            'rs("kpi1") = True 'The other way to refer to a field

            'Save contact name into a variable
            'sContactName = rs!staffName & " " & rs!staffID
            'rs!kpi3 = sContactName
            rs.Update
            'Move to the next record. Don't ever forget to do this.
            rs.MoveNext
        Loop
    Else
        MsgBox "There are no records in the recordset."
    End If

    MsgBox ("Finished looping through records." & Environ$("username"))

    rs.Close 'Close the recordset
    Set rs = Nothing 'Clean up
È stato utile?

Soluzione

it will be one record found

use this code:

Dim rs As DAO.Recordset
Dim sqlStr As String

sqlStr = "SELECT * FROM agentKPI WHERE staffName = '" & Environ$("username") & "'"
Set rs = CurrentDb.OpenRecordset(sqlStr)

'Check to see if the recordset actually contains rows
If Not (rs.EOF And rs.BOF) Then
    Forms!agentKPI!Label10.Caption = rs("staffName")
    Forms!agentKPI!Label14.Caption = rs("kpi1")
    Forms!agentKPI!Label23.Caption = rs("kpi2")
    Forms!agentKPI!Label26.Caption = rs("kpi3")
Else
    MsgBox "There are no records in the recordset."
End If

MsgBox "Finished looping through records. " & Environ$("username")

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top