I am trying to accomplish the following:
Use VBA to loop through a table, and assign people to be seated at dinner tables using the following three parameters:
1) The individual's priority score.
2) The individual's preferences on what table to be seated at.
3) The seating capacity of the table.
Ideally, the VBA would start from the 1st record of Priority 1 group, assign as many people as can be placed in Table1, and then continue assigning Priority 1 individuals according to their preference, while checking to see if their preferred tables are at capacity.
After all Priority 1 individuals are assigned a table (given a 'Table_Assignment' value in the table object), the VBA moves to Priority 2 individuals, and so forth.
In my database, I have the following table (table object called 'tbl_Assignments'):
RecordID | Table_Assignment | Priority | Title | Preference_1 | Preference_2 |... Preference_n
001 1 CEO Table1
002 1 CEO-spouse Table1
003 1 VP Table1 Table2
004 1 VP-spouse Table1 Table2
005 2 AVP Table1 Table2
006 2 AVP-spouse Table1 Table2
007 3 Chief counsel Table1 Table2 Table_n
008 3 COO Table1 Table2 Table_n
Additionally, I have created a query tells you how many vacancies are left as assignments to tables are being made (query object called 'qry_capacity_sub1'):
TableID | Maximum_seating | Seats_taken | Vacancies
Table1 4 3 1
Table2 4 2 2
Table3 4 0 4
Table4 4 1 3
I have attempted to write VBA, with a loop, that would accomplish my goal of looping through the table ('tbl_Assignments') and assigning values for the 'Table_Assignment' field once a command button is clicked on a form.
Update (11/09/2014): Updated the VBA to where I am in this process now. The changes to the VBA also reflect Jérôme Teisseire's suggestion.
The following VBA started from what I saw here: Looping Through Table, Changing Field Values
Private Sub Command0_Click()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb()
strSQL = "Select RecordID, Table_Assignment, Priority, Preference_1, Preference_2, Preference_3 FROM tbl_Assignments WHERE Priority =1"
Set rs = db.OpenRecordset(strSQL)
On Error GoTo Err_Handler
Do Until rs.EOF
With rs
If there are seats available at your first preferred table Then
.Edit
!Table_Assignment = rs!Preference_1
.Update
.MoveNext
End If
If the first table you preferred has reached capacity, and there are seats left in your second preferred table Then
.Edit
!Table_Assignment = rs!Preference_2
.Update
.MoveNext
End If
'..keep checking each the person's preferred tables. If they cannot be assigned a table because their preferred tables are at capacity...
Else
.Edit
!Table_Assignment = "Unassigned"
.Update
.MoveNext
End With
Loop
rs.Close
Exit_Handler:
Set rs = Nothing
Set db = Nothing
Exit Sub
Err_Handler:
MsgBox "You need to debug"
Resume Exit_Handler
End Sub