MS Access - 如何将项目添加到列表框和 Select 仅在 Recordset 中找到的项目

MS Access - How to Add Items to List Box and Select only Items that are found in Recordset

我有一个由记录集填充的列表框。然后我试图 select 基于另一个记录集中的值的列表框中的项目。我能够填充列表框,但是当我尝试 select 基于另一个记录集的值时,列表框 Me.ToolUsed1 为 Null。我调用另一个函数来 selecting 值,因为我计划对其他列表框使用相同的过程。非常感谢您提供的任何帮助。

           'Populate the tool list box
            While Not rsToolList.EOF
                Me.ToolUsed1.AddItem Item:=rsToolList.Fields(0)
                rsToolList.MoveNext
            Wend

            matchKey = "MatchKey = """ & rsActivities.Fields(0) & """"

            If rsTools.RecordCount > 0 Then
                rsTools.MoveFirst
                rsTools.FindFirst (matchKey)

                toolIndex = rsTools.Fields(2)
                While Not rsTools.EOF
                    If (rsTools.Fields(2) = toolIndex) Then
                        SelectListValues Me.ToolUsed1, rsTools.Fields(1)
                    End If
                    rsTools.MoveNext
                Wend
            End If

Private Sub SelectListValues(tempListBox As Object, selectString As String)
Dim i As Integer
Dim found As Boolean

i = 0
found = False

 'select the value in the listbox
    While i < tempListBox.ListCount And Not found
      If tempListBox.Value(i) = selectString Then
          tempListBox.Selected(i) = True
          found = True
       End If
       i = i + 1
  Wend

  'if the string wasn't found, add it 
  If Not found Then
     tempListBox.AddItem (selectString)
  End If
End Sub

考虑为您的列表框使用查询记录源,而不是要添加的值项。像组合框这样的列表框维护 RowSource 属性,允许 Table/Query 来源,您可以将其设置为第一个记录集 rsToolList。然后,只打开一个记录集,rsTools,循环遍历它来决定选择的项目。请注意,对于 table/query 来源,绑定列是列表框的值,而不是任何其他列。

' POPULATE TOOL LIST BOX TO QUERY
Me.tempListBox.RowSource = "ToolList"       ' OR USE SELECT SQL STATEMENT HERE
Me.tempListBox.RowSourceType = "Table/Query"
Me.tempListBox.Requery

' LOOP THROUGH LISTBOX AND RECORDSET FOR SELECTED ITEMS 
Dim rsTools As Recordset, i As Integer

Set rsTools = CurrentDb.OpenRecordset("Tools", dbOpenDynaset)

rsTools.MoveLast
rsTools.MoveFirst

If rsTools.RecordCount > 0 Then
    While Not rsTools.EOF
       i = 1
       While i < Me.tempListBox.ListCount
           ' CHANGE C FUNCTION HERE TO NEEDED TYPE: CLng, CInt, CStr, CDate, ...
           If CLng(Me.tempListBox.ItemData(i)) = rsTools.Fields(1) Then
               Me.tempListBox.Selected(i) = True
           End If
           i = i + 1
       Wend
       rsTools.MoveNext
    Wend
End If

rsTools.Close
Set rsTools = Nothing