
Originally Posted by
virgilio
How do I access the next record with each loop?
This is how I would write the VBA
Code:
Private Sub My_Function_Click()
'On Error GoTo Error_Handler
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim i As Integer
Dim LOT_NUMBER As Long 'does not need delimiters because it is a Number
Dim Location As String 'requires delimiters because it is a String
Dim strSQL As String
Set db = CurrentDb()
LOT_NUMBER = 12345
Location = "here"
Set rs = db.OpenRecordset("LOT_DATES")
If Not rs.BOF And Not rs.EOF Then '<<--- always check to see if there are records in the recordset
rs.MoveLast
rs.MoveFirst
Do Until rs.EOF
' For i = 0 To rs.RecordCount - 1
LOT_NUMBER = rs![LOT_NUMBER]
strSQL = "INSERT INTO Lot_Location (Lot_Num, Location) VALUES (" & LOT_NUMBER & ", '" & Location & "' );" '<<-- notice the delimiters
' DoCmd.RunSQL strSQL
db.Execute strSQL, dbFailOnError
rs.MoveNext
' Next i
Loop
Else
MsgBox "No records found"
End If
'clean up
rs.Close
Set rs = Nothing
Set db = Nothing
End Sub
This is what June7 suggested (Faster than looping)
Code:
Private Sub My_Function_Click()
Dim Location As String 'requires delimiters because it is a String
Dim strSQL As String
Location = "here"
strSQL = "INSERT INTO Lot_Location(Lot_Num, Location) SELECT Lot_Number, '" & Location & "' FROM LOT_DATES"
'or, since location is static text, you could use
' strSQL = "INSERT INTO Lot_Location(Lot_Num, Location) SELECT Lot_Number, 'here' FROM LOT_DATES"
CurrentDb.Execute strSQL, dbFailOnError
End Sub
Since "Location" is static text, you could use
Code:
strSQL = "INSERT INTO Lot_Location(Lot_Num, Location) SELECT Lot_Number, 'here' FROM LOT_DATES"
Then you wouldn't need the variable "Location" in the code.