In AC97, I have a form frmAddNewTrainNo with tbxTrainYear, tbxTrainNoStart, tblTrainNoFinish that is used to add new train numbers to tblTrain. There is also a lbxTrainNoYear with a record source query that displays the last train number's TrainYear and TrainNo. The user is supposed to enters values into tbxTrainYear, tbxTrainNoStart, and tbxTrainNoFinish for the next train numbers to add. However, if a pre-existing TrainYear and TrainNo are entered, the duplicate train number will be added to the tblTrain.
In tblTrain, there are fields TrainID, TrainYear, and TrainNo. Each train number is made up of TrainYear and TrainNo. In tblTrain I only want one record with each TrainYear-TrainNo pair.
I have the following code, but my "If" statement doesn't prevent the inclusion of duplicate TrainYear-TrainNo pairs.
Any suggestions?
Thanks,
Brian
In tblTrain, there are fields TrainID, TrainYear, and TrainNo. Each train number is made up of TrainYear and TrainNo. In tblTrain I only want one record with each TrainYear-TrainNo pair.
I have the following code, but my "If" statement doesn't prevent the inclusion of duplicate TrainYear-TrainNo pairs.
Code:
Private Sub cmdAddRecord_Click()
On Error GoTo Err_cmdAddRecord_Click
DoCmd.SetWarnings True
Dim AddTrainNo As Long, SQL1 As String
Dim lngTrainNoStart As Long
Dim lngTrainNoEnd As Long
Dim lngTrainYear As Long
lngTrainNoStart = Me!tbxTrainNoStart
lngTrainNoEnd = Me!tbxTrainNoFinish
lngTrainYear = Me!tbxTrainYear
For AddTrainNo = lngTrainNoStart To lngTrainNoEnd
If lngTrainYear = [TrainYear] And lngTrainNoStart = [TrainNo] Then
MsgBox "Train number already exists!", vbInformation, "Selection Error"
Exit Sub
Me.Undo
End If
SQL1 = "INSERT INTO tblTrain (TrainYear,TrainNo) " & _
"VALUES(" & lngTrainYear & "," _
& AddTrainNo & ");"
Debug.Print SQL1
DoCmd.RunSQL SQL1
Next
DoCmd.SetWarnings True
Exit_cmdAddRecord_Click:
Exit Sub
Err_cmdAddRecord_Click:
MsgBox Err.Description
Resume Exit_cmdAddRecord_Click
End Sub
Any suggestions?
Thanks,
Brian