I want to insert x records to a table based on some fields in a form, where x is a number entered by the user.
Seemed, simple, based on my code below. However, when I run the code, it writes the first record correctly, then writes the second record twice, the third record four times, the fourth record eight times....
Is there a problem using DoCmd.RunSQL in a For...Next loop? I know there are probably fancier ways using recordsets, etc, but for the purpose, RunSQL (almost!) works fine.
Seemed, simple, based on my code below. However, when I run the code, it writes the first record correctly, then writes the second record twice, the third record four times, the fourth record eight times....
Is there a problem using DoCmd.RunSQL in a For...Next loop? I know there are probably fancier ways using recordsets, etc, but for the purpose, RunSQL (almost!) works fine.
Code:
' Delete any existing temp records
Dim ssql As String
ssql = "DELETE [CSO Guarantee Details].*, [CSO Guarantee Details].Temp FROM [CSO Guarantee Details] WHERE ((([CSO Guarantee Details].Temp)=Yes))"
DoCmd.RunSQL (ssql)
' Add new temp records
Dim i As Integer, Months As Integer
Dim CSOCode As String, SMonth As String
CSOCode = Me.cmbCSO.Value
Months = Me.txtDuration
For i = 0 To Months - 2
PDate = DateAdd("m", i, Me.txtStartDate)
SMonth = Format(DateAdd("m", -1, PDate), "mmm")
PaidComm = Me.txtPerAmount
ssql = "INSERT INTO [CSO Guarantee Details] ( CSOCode, [Payment Date], [Sales Month], [Paid Commission], Temp ) SELECT '" & CSOCode & "' AS A, " & PDate & " AS B, '" & SMonth & "' AS C, " & PaidComm & " AS D, Yes AS Expr1 FROM [CSO Guarantee Details]"
DoCmd.RunSQL ssql
Next
' Add the last record to ensure last amount is correct (rounding)
PDate = DateAdd("m", i + 1, Me.txtStartDate)
SMonth = Format(DateAdd("m", -1, PDate), "mmm")
PaidComm = Me.txtTotalValue - (Me.txtPerAmount * (Me.txtDuration - 1))
ssql = "INSERT INTO [CSO Guarantee Details] ( CSOCode, [Payment Date], [Sales Month], [Paid Commission], Temp ) SELECT '" & CSOCode & "' AS A, " & PDate & " AS B, '" & SMonth & "' AS C, " & PaidComm & " AS D, Yes AS Expr1 FROM [CSO Guarantee Details]"
DoCmd.RunSQL ssql