How do I use Access VBA to update a multivalue field

后端 未结 1 1072
广开言路
广开言路 2021-01-27 10:22

I\'m writing a script that takes printouts from another software product, parses the data and then imports the training event. Here\'s a sample bit of data that I\'m working wi

相关标签:
1条回答
  • 2021-01-27 10:41

    I know this is over a year old and you may have already found your solution, but for those who came here looking for a potential solution to a similar problem, I have one solution that should work based on the information you provided.

    Before I post the code the first thing we need to understand is that when dealing with a Multi Value Field in VBA we need to treat it as a Child Recordset with the Table Record being its Parent. This means it needs to be declared after we navigate to the appropriate record. In your case:

    Dim rst As DAO.Recordset2
    Dim asp As DAO.Recordset
    ...
    rst.AddNew
    Set asp = rst.AssignedPersonnel.Value
    ...
    

    Second, a common misconception is that since in the Table we assign a Record Source to the Multi Value Field we just need to toggle what records apply to the field as we would do manually. Sadly, this is not the case as the record source is only a Data Validation Tool and does not inherently populate the Multi Value Field with data. In your case, as you are creating a new record, this field is empty.

    Third, we need to understand that a Recordset that is set to the value of a Multi Value Field is only a Single Field Recordset which, as far as I know, is not provided with a field name and must be referenced by the Field ID number which is 0.

    Finally, when adding data to the Multi Value Field Recordset, we need to do so as a Recordset.

    So without further ado, here is a possible solution which works for me:

    Public Sub Solution()
    
    Dim cdb As DAO.Database ' Database
    Dim imt As DAO.Recordset ' Import Table
    Dim rst As DAO.Recordset2 ' Events Table
    Dim asp As DAO.Recordset ' Multi Value Field
    
    Set cdb = CurrentDb
    Set rst = cdb.OpenRecordset("tblEvents", dbOpenTable)
    Set imt = cdb.OpenRecordset("tblImport", dbOpenTable)
    
    rst.AddNew  'Add new record to Events Table
    
    Set asp = rst!AssignedPersonnel.Value ' Set asp to the AssignedPersonnel Field Value for the new Events Table Record.
    
    Do While Not imt.EOF ' Cycle through the Import Table Records
        asp.AddNew ' Add a new record to the asp Recordset
        asp.Fields(0) = imt!EmpID
        asp.Update ' Commit the changes to the asp Recordset
        imt.MoveNext
    Loop
    
    rst.Update ' Commit the changes to the Events Table Recordset
    
    End Sub
    
    
    0 讨论(0)
提交回复
热议问题