列表框加载的数据多于

时间:2015-10-04 20:29:49

标签: ms-access access-vba ms-access-2010

我在表单上有一个列表框,使用以下代码加载,只能从form_load事件中调用一次。

Private Sub LoadList()

  Dim rs As DAO.Recordset
  Dim db As DAO.Database
  Dim strSQL As String
  Dim condition As String

  Set db = CurrentDb

  condition = " WHERE Schedule_ID = " & ScheduleID

  strSQL = "SELECT Shifts.Shift_ID, Shifts.Start_Date_Time, Shifts.End_Date_Time, Locations.Location_Name FROM Shifts, Locations " & _
"WHERE Schedule_ID = " & ScheduleID & " AND Locations.Location_ID = Shifts.Location ORDER BY Start_Date_Time"

  'Set Recordset Query
  Set rs = db.OpenRecordset(strSQL)

  RecCount = recordCount("Shifts", condition)
  Me.lblCount.Caption = "Shift Count: " & RecCount

  rs.MoveFirst
  For i = 0 To RecCount - 1
    Me.lstShifts.AddItem rs!Shift_ID & ";" & rs!Start_Date_Time & " TO " & rs!End_Date_Time & " AT " & rs!Location_Name
    rs.MoveNext
  Next i

  'Close Connections and Reset Variables
  rs.Close
  Set rs = Nothing
  Set db = Nothing

  listdirty = False
End Sub

数据库中只有十条记录,但列表框加载数据三次(总共30条)。我逐步完成了代码并在RecCount变量上将其初始化为10,for循环按预期迭代10次。这个LoadList子不会被多次调用,所以我不明白为什么记录多次出现在列表框中。有任何想法吗?

1 个答案:

答案 0 :(得分:2)

每次调用LoadList()过程时,它都会向列表框中添加行。由于列表框包含30行,尽管源记录集仅包含10行,因此LoadList()被调用3次,或者您使用非空值列表保存表单并在每个表单中再添加10行负载

您可以通过在执行RowSource的循环之前清空AddItem值列表来避免此问题...

rs.MoveFirst
Me.lstShifts.RowSource = vbNullString ' make sure value list starts empty
For i = 0 To RecCount - 1
    Me.lstShifts.AddItem rs!Shift_ID & ";" & rs!Start_Date_Time & " TO " & rs!End_Date_Time & " AT " & rs!Location_Name
    rs.MoveNext
Next i

但是,您的查询几乎就是您希望列表框显示的内容。修改该查询并将其用作列表框RowSource

应该更简单
  1. 将列表框的RowSourceType属性从“值列表”更改为“表/查询”
  2. 确保列表框的列计数属性设置为2。
  3. LoadList()程序中,将查询字段列表修改为SELECT Shifts.Shift_ID, Shifts.Start_Date_Time & ' TO ' & Shifts.End_Date_Time & ' AT ' & Locations.Location_Name
  4. 最后,将更新的查询分配给列表框的RowSource属性:Me.lstShifts.RowSource = strSQL