将表单信息添加到表中

问题描述 投票:1回答:2
Option Compare Database

Private Sub cmdAdd_Click()
    CurrentDb.Execute "INSERT INTO Overtime(Todays_Date, Employee_Name, " & _
        "Start_Date, End_Date,Comments) " & _
        " VALUES(" & Me.txtCurrentday & ",'" & Me.txtName & "','" & _
        Me.txtBegin & "','" & Me.txtEnd & "','" & Me.txtComment & "')"

    Me.Refreshenter        
    cmdClear_Click
End Sub

Private Sub cmdClear_Click()
    Me.txtCurrentday = ""
    Me.txtName = ""
    Me.txtBegin = ""
    Me.txtEnd = ""
    Me.txtComment = ""

    Me.txtCurrentday.SetFocus
End Sub

Private Sub cmdClose_Click()
    DoCmd.Close
End Sub

您好,我已在Microsoft Access 2010中创建了一个表单和一个表。该表单称为pbicovertime它有五个未绑定的文本框,它们都有唯一的名称和三个按钮。我希望在按下“添加”按钮时,将表单中输入的信息添加到名为“加班”的表中。上面的代码确实将表单中的数据添加到表中,但是我得到了运行计时器错误“3061”:参数太少。关闭并重新打开数据库后预计出现1条错误消息。所以最初一切似乎都运行正常。在表格中输入的所有信息都被添加到我的加班表中的正确列中。问题发生在关闭并重新打开数据库之后。我不确定如何从这一点开始。

仅供参考我这是第一次使用Forms in Access!

forms ms-access access-vba
2个回答
1
投票

打开您的表作为记录集并添加一行。这将避免基于您添加的值中的必需/缺少引号或日期分隔符的复杂性。

Option Compare Database
Option Explicit ' <- add this

Private Sub cmdAdd_Click()
    Dim db As DAO.database
    Dim rs As DAO.Recordset
    Set db = CurrentDb
    Set rs = db.OpenRecordset("Overtime",  dbOpenTable, dbAppendOnly)
    With rs
        .AddNew
        !Todays_Date = Me.txtCurrentday
        !Employee_Name = Me.txtName
        !Start_Date = Me.txtBegin
        !End_Date = Me.txtEnd
        !Comments = Me.txtComment
        .Update
        .Close
    End With
    'Me.Refreshenter ' <- what is this?
    cmdClear_Click
End Sub

如果原始缺失参数错误是由于拼写错误的字段名称,则此代码将在AddNewUpdate之间的某一行上引发错误,因此您应该能够快速识别错误拼写的名称。

注意:始终在代码模块的声明部分中包含Option Explicit。然后从VB Editor的主菜单中运行Debug-> Compile。在花时间对代码进行故障排除之前,纠正编译器抱怨的任何内容。

我不知道Me.Refreshenter是什么。它看起来像Me.Refresh拼写错误。如果是这样,那就是Option Explicit会警告你的事情。但是,如果你想要Refresh,我建议你替换Me.Requery。原因是Refresh将对表单记录集中的任何现有行进行更改,而不是新添加的行。除了对现有行的更改外,Requery还会获得新行。


0
投票

我愿意打赌这条线正在崩溃。

CurrentDb.Execute "INSERT INTO Overtime(Todays_Date, Employee_Name, " & _
    "Start_Date, End_Date,Comments) " & _
    " VALUES(" & Me.txtCurrentday & ",'" & Me.txtName & "','" & _
    Me.txtBegin & "','" & Me.txtEnd & "','" & Me.txtComment & "')"

特别是Me.txtCurrentday,因为它将被评估为直接文本,并且根据您的PC设置方式,它可能会使SQL混淆。例如,它可能看起来像这样:

INSERT INTO Overtime(Todays_Date, Employee_Name, Start_Date, End_Date,Comments) 
VALUES ( Dec 1, 2013, 'JoeSmith', 'Jan 1, 2013', 'Dec 31, 2013', 
'Some important comment');

你应该包含在#的日期:

INSERT INTO Overtime(Todays_Date, Employee_Name, Start_Date, End_Date,Comments) 
VALUES ( #Dec 1, 2013#, 'JoeSmith', #Jan 1, 2013#, #Dec 31, 2013#, 
'Some important comment');

它会变得更顺畅。同样以这种方式构建SQL会使您容易受到注入(无论是攻击还是错误)。想象一下,如果评论是“这是苏西的工作”,在这种情况下额外的撇号会弄乱插入。

© www.soinside.com 2019 - 2024. All rights reserved.