访问VBA循环并显示偏移记录数据

时间:2014-04-05 18:39:39

标签: loops access-vba ms-access-2007

我正在编写循环记录的vba代码,如果记录等于环境用户名,则在标签中显示的表单中显示找到的用户名的偏移记录。

到目前为止,我遇到了一堵砖墙,试图获取属于匹配用户名的值。

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

1 个答案:

答案 0 :(得分:0)

  

将会找到一条记录

使用此代码:

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