【问题标题】:MS Access - How to Add Items to List Box and Select only Items that are found in RecordsetMS Access - 如何将项目添加到列表框并仅选择在记录集中找到的项目
【发布时间】:2016-04-21 10:57:34
【问题描述】:

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

           '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

【问题讨论】:

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


    【解决方案1】:

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

    ' 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      相关资源
      最近更新 更多