I need some help with some VBA for Access.
I have a table "Client_Table"
with 100 rows of data. I have another table "SalesRep_Table"
where I have 10 distinct Sales Rep ID numbers (such as: AA1111
, and so on).
My goal is to run a procedure that takes the first ID record "AA1111"
and places it in the appropriate column on the Clients table named "AssignedSalesRepID"
for the first 10 rows, then the next ID number in the SalesRep_Table
gets inserted into the next 10 cells in the Clients
table, and the process repeats through a loop until all 10 IDs are now in 10 rows each to fill the 100 rows of data in the Clients table.
I went about it by creating two recordsets and trying a loop through SQL Update. However I end up with all 100 records containing just the last Sales Rep ID 100 times repeating. Can you take a look at my code and let me know where it needs to be fixed?
Public Sub Command01_Click()
Dim strSQL
Dim ClientsTableQuery, SalesRepList
Dim DataB as Database
Dim ClientQD as QueryDef
Dim SalesQD as QueryDef
Dim rstClient as Recordset
Dim rstSalesRep as Recordset
ClientTableQuery = "Clients"
SalesTableQuery = "SalesRepList"
'Creates a recordset with 100 client records named "Clients"
strSQL = "Select * from Client_Table"
Set DataB = CurrentDB()
Set ClientQD.CreateQueryDef(ClientTableQuery, strSQL)
Set rstClient = DataB.OpenRecordset(ClientTableQuery)
'Creates a recordset with 10 sales rep records named "SalesRepList"
strSQL = "Select SalesRepID from SalesRep_Table"
Set DataB = CurrentDB()
Set SalesQD.CreateQueryDef(SalesTableQuery, strSQL)
Set rstSalesRep = DataB.OpenRecordset(SalesTableQuery)
rstSalesRep.MoveFirst
rstClient.MoveFirst
Do Until rstSalesRep.EOF = True
'SQL Query to update the top 10 cells in the "Assigned Sales Rep ID" column in the
Clients recordset with the Sales Rep ID from the SalesRepList recordset
strSQL = "Update Clients, SalesRepList SET Clients.AssignedSalesRepID =
SalesRepList.SalesRepID where Clients.ClientIDNumber in (Select Top 10
Clients.ClientIDNumber FROM Clents where Clients.AssignedSalesRepID is Null)"
DoCmd.RunSQL (strSQL)
rstSalesRep.MoveNext
Loop
MsgBox "Finished Looping"
rstSalesRep.Close
End Sub