Microsoft Access VBA 将数据从表单添加到未绑定表单的表

Microsoft Access VBA add data from form to tables unbound form

如何使用代码生成的数据和用户输入将记录添加到 deploymentStep table 和 deploymentPlan table?

我有table像下面这样的

PillarTeamDeploymentSteps

pillarTeam pillarTeamStep other info
team 1 step 1
team 1 step 2
team 1 step 3
team 1 step 4
team 2 step 1
team 2 step 2
team 2 step 3
team 2 step 4
team 2 step 5
team 2 step 6

和table结构

deploymentStep

pillarTeam pillarTeamStep deployment endDate

部署计划

pillarTeam deployment startDate endDate

使用表单我希望用户能够 select 他们的团队并让它使用相应的 pillarTeamSteps 自动填充文本字段。这可以在屏幕截图中看到。

在用户 select 编辑团队并且步骤自动填充后,他们将在日期框中手动输入数据。从这里我想按一下按钮来添加记录。我正在使用以下代码来更新表单可见字段和值。每队最多只能走十步。

如何使用代码生成的数据和用户输入将记录添加到 deploymentStep table 和 deploymentPlan table?

Private Sub pillarTeam_AfterUpdate()
Dim db As DAO.Database
Dim RS As DAO.Recordset
Dim deploymentSteps As DAO.Recordset

Set db = CurrentDb

strSQL = "SELECT PillarTeamDeploymentSteps.pillarTeam, PillarTeamDeploymentSteps.pillarTeamStep, PillarTeamDeploymentSteps.deploymentType FROM PillarTeamDeploymentSteps WHERE (((PillarTeamDeploymentSteps.pillarTeam)=" & Me.pillarTeam & "))"

Debug.Print (strSQL)

Set RS = db.OpenRecordset(strSQL)
If Not (RS.EOF) Then
    RS.MoveLast
    RS.MoveFirst
End If



'setting visible controls
Dim ctl As Control
For Each ctl In Me.Controls
    If ctl.Tag < RS.RecordCount + 1 Or (ctl.Tag < RS.RecordCount + 21 And ctl.Tag >= 20) Then
        ctl.Visible = True
    Else
        ctl.Visible = False
    End If
Next ctl


With RS
    If Not .BOF And Not .EOF Then
    .MoveLast
    .MoveFirst
    While (Not .EOF)
        Debug.Print (RS.AbsolutePosition)
'populating deployment steps
        For Each ctl In Me.Controls
            If ctl.Tag = RS.AbsolutePosition Then
                ctl.Value = RS.Fields("pillarTeamStep")
            End If
            
         Next ctl
          
        .MoveNext
    Wend
        
        
    End If
    .Close
End With
    

    Set RS = Nothing
    Set db = Nothing

建议将表单绑定到 deploymentPlan 并将子表单绑定到 deploymentStep。

要 'batch' 创建记录,请使用 INSERT SELECT 操作 SQL。

CurrentDb.Execute "INSERT INTO deploymentStep(pillarTeam, pillarTeamStep, deployment) " & _
                   "SELECT " & Me.tbxTeam & " AS T, pillarTeamStep, " & Me.tbxDeploymentID & " AS D " & _
                   "FROM PillarTeamDeploymentSteps " & _
                   "WHERE pillarTeam=" & Me.tbxTeam

这假设 pillarTeam 和 deployment 是数字标识符,例如 Autonumber 类型。如果不是,则使用撇号分隔符。

这里的技巧是首先保存 'parent' deploymentPlan 记录并获取该记录标识符以在 deploymentStep 中保存为外键。