你没有提到每个表中的主键是什么,所以我假设它是user 字段,并且t_main 和t_saved 中的每条记录都有一个唯一的user。
如果不是,则将其替换为实际的主键。
请注意,date 是保留关键字,您不能将字段命名为 date,因此我将其重命名为 thedate。
我创建了一个small sample database,它的工作方式与您描述的一样(至少据我了解)。
我用一些示例数据创建了这些表:
我创建了一个绑定到t_main 表的表单:
请注意,下拉框 cbParam1 和 cbParam2 未绑定到任何字段,它们是未绑定。
下拉框的行源有点小技巧,但效果很好。
例如,对于cbParam1.RowSource:
SELECT param1_old
FROM t_main
WHERE user=Forms![FormMain]![User]
UNION ALL
SELECT param1_new
FROM t_main
WHERE user=Forms![FormMain]![User];
此查询从t_main 记录中选择与当前显示的具有相同user 的旧字段和新字段。实际上,它会在组合框中显示当前记录的旧参数和新参数。
FormMain后面的代码主要用于管理显示。
如果下拉框之一为空,或者我们之前已经添加过该记录,我们将阻止用户将数据添加到 t_saved。
Option Compare Database
Option Explicit
' We use this variable to keep track of whether the
' record was already found in the t_saved table
Private alreadysaved As Boolean
'-----------------------------------------------------------------------------
' Update the UI after we change our selection of parameter
'-----------------------------------------------------------------------------
Private Sub cbParam1_AfterUpdate()
UpdateUI
End Sub
Private Sub cbParam2_AfterUpdate()
UpdateUI
End Sub
'-----------------------------------------------------------------------------
' Enable/Disable the save button.
' The button is only enabled if the user selected both parameters
'-----------------------------------------------------------------------------
Private Sub UpdateUI()
btAddData.Enabled = Not (IsNull(cbParam1) Or IsNull(cbParam2)) _
And Not alreadysaved
End Sub
'-----------------------------------------------------------------------------
' Refresh teh data every time we change record
'-----------------------------------------------------------------------------
Private Sub Form_Current()
' Reset the values of the parameters comboboxes
cbParam1 = Null
cbParam2 = Null
cbParam1.Requery
cbParam2.Requery
' Check if there is already a record for the same user in the t_save table
alreadysaved = DCount("user", "t_saved", "user='" & user & "'") > 0
' Display a warning to tell the user the current record cannot be saved again
lblInfo.Visible = alreadysaved
UpdateUI
End Sub
重要的代码实际上是将数据添加到t_saved表中的新记录:
'-----------------------------------------------------------------------------
' The button was clicked.
' Save the current record data to the t_save table
'-----------------------------------------------------------------------------
Private Sub btAddData_Click()
' We create a new new record in t_save and copy our data
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("t_saved", dbOpenDynaset, dbFailOnError)
With rs
.AddNew
!user = user
!thedate = thedate
!name = name
!param1 = cbParam1
!param2 = cbParam2
.Update
.Close
End With
Set rs = Nothing
Set db = Nothing
' Force the form to refresh itself
' This will cause the Form's OnCurrent event to be triggered
Me.Requery
End Sub