通过VBA MS Access将多值列的数据绑定到组合框中

时间:2019-12-11 09:54:28

标签: vba ms-access combobox

我有一张桌子,如下表

enter image description here

BranchIds列是引用分支表的ID的多值列。 我需要如何将id及其相关值绑定在另一个访问表单中的组合框中,如下所示 enter image description here

权限表包含允许哪个用户访问哪个分支的数据。 我无法以另一种形式将蠕虫表的分支绑定到组合框。

  

我正在尝试的代码。经过长度搜索后从MSDN获得。

Sub BindBranches()
   Me.comboBranchIds.RowSourceType = "Value List"

   Dim db As Database
   Dim rs As Recordset
   Dim childRS As Recordset

   Set db = CurrentDb()

   ' Open a Recordset for the Tasks table.
   Set rs = db.OpenRecordset("SELECT BranchIds FROM Permissions WHERE UserId = " & Forms!NavigationForm!txtSession.Value)
   rs.MoveFirst

   Do Until rs.EOF
      ' Print the name of the task to the Immediate window.
      'Debug.Print rs!TaskName.Value

      ' Open a Recordset for the multivalued field.
      Set childRS = rs!BranchIds.Value

         ' Exit the loop if the multivalued field contains no records.
         Do Until childRS.EOF
             childRS.MoveFirst

             ' Loop through the records in the child recordset.
             Do Until childRS.EOF
                 ' Print the owner(s) of the task to the Immediate
                 ' window.
                 'Debug.Print Chr(0), childRS!Value.Value
                 Me.comboBranchIds.AddItem Item:=childRS!Value.Value
                 'Me.comboBranchIds.RowSource = "SELECT BranchName FROM Branches WHERE ID = " + childRS!Value.Value
                 childRS.MoveNext
             Loop
         Loop
      rs.MoveNext
   Loop
End Sub

1 个答案:

答案 0 :(得分:1)

MultiValue字段与值列表无关。

只需使用MultiValue字段的 RowSource 属性,例如:

SELECT [TableName].[FieldName] FROM [TableName] ORDER BY [Id];

作为组合框的 RowSource 属性。

具有过滤器:

SELECT [TableName].[FieldName] 
FROM [TableName] 
WHERE UserId = [Forms]![NavigationForm]![txtSession]
ORDER BY [Id];

或通过代码将SQL修改为:

SELECT [TableName].[FieldName] 
FROM [TableName] 
WHERE UserId = 466
ORDER BY [Id];

应用修订的SQL将自动重新查询组合框。