I am trying to write a program to randomly select 20 subjects from 20 groups. All groups and subjects are in one table. The variable for group is SecondaryID and the variable for subject is SubjectID. I found some code online that works for the random selection but have been unable to modify the code to do this for each SecondaryID. Any suggestions would be much appreciated.
Thanks!
Thanks!
Code:
Option Compare Database
Sub PickRandom()
Dim db As Database
Dim tdf As TableDef
Dim fld As Field
Dim rst As Recordset
Dim strSQL As String
Dim strTableName As String
' 1: Create a new temporary table containing the required fields
strSQL = "SELECT tblDATA.SecondaryID, tblDATA.SubjectID " & _
"INTO tblTemp " & _
"FROM tblDATA;"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
' 2: Add a new field to the new table
Set db = CurrentDb()
Set tdf = db.TableDefs("tblTemp")
Set fld = tdf.CreateField("RandomNumber", dbSingle)
tdf.Fields.Append fld
' 3: Place a random number in the new field for each record
Set rst = db.OpenRecordset("tblTemp", dbOpenTable)
rst.MoveFirst
Do
Randomize
rst.Edit
rst![RandomNumber] = Rnd()
rst.Update
rst.MoveNext
Loop Until rst.EOF
rst.Close
Set rst = Nothing
' 4: Sort the tblTemp by the random number and move the top 20 into a new table
strTableName = SecondaryID & Format(Date, "ddmmmyyyy")
strSQL = "SELECT TOP 20 tblTemp.secondaryID, tblTemp.SubjectID " & _
"INTO " & strTableName & " " & _
"FROM tblTemp " & _
"ORDER BY tblTemp.RandomNumber;"
DoCmd.SetWarnings False
DoCmd.RunSQL strSQL
DoCmd.SetWarnings True
' 5: Delete the temporary table
db.TableDefs.Delete ("tblTemp")
End Sub
Comment