【问题标题】:Access VBA loop and show offset record data访问 VBA 循环并显示偏移记录数据
【发布时间】:2014-04-05 18:39:38
【问题描述】:

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

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

    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

【问题讨论】:

  • 每个Environ$("username")的表中是否可以有多个记录?
  • 目的是为登录的人显示 kpi 结果。所以它会找到一条记录
  • 您只有 3 个 kpi:kpi1,kpi2,kpi3,但有 4 个标签。第四个标签应该是什么?还有什么是agentKPI,表单还是子表单?
  • agentkpi 是一个访问表单,第四个标签将显示代理名称

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


【解决方案1】:

将找到一条记录

使用此代码:

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

【讨论】:

  • 我运行代码,出现错误信息无效使用我!
  • 代码放在哪里?在 form 模块还是在 standart 模块中?试试我更新的代码
  • 我已经创建了一个名为 module1 的外部宏,并且我已经为 command4“显示结果按钮”生成了一个过程,我已经放置了宏名称 getkpidetails
  • 你用Forms!agentKPI!代替Me!尝试了我的更新代码吗?
  • 感谢@simoco,几秒钟后代码开始工作,我很快谷歌找到了相同的答案。 google.co.uk/…
猜你喜欢
  • 2018-05-16
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多