向指定表插入值的SQL语句语法错误

问题描述 投票:0回答:1

我在 VBA(Access 数据库)中创建了一条 SQL 插入语句。

我创建了一个子程序,在单击按钮时运行,并期望将值插入到指定的表中。

我收到语法错误。

Private Sub addAllocation_Click()
    Dim strSQL, user_id As String
    Dim rs As Recordset
    UserID = Left(Environ("USERNAME"), 15)
    If Me.newEffectiveDate = "" Or Me.newAmount = "" Then
        MsgBox "Please complete all required fields"     
    End If
        
    strSQL = "INSERT INTO Participant_Allocation(Transaction_ID, Participant_ID, Loan_ID, Allocation_Amount, " & _
      "Effective Date, Notes, user_ID) " & _
      "VALUES('" & Me.txtTransactionID & "' , '" & Me.cmbParticipantID.Column(3) & "' , '" & Me.cmbLoan & "' , '" & _
      Me.newAmount & "' , '" & Me.newEffectiveDate & "' , '" & Me.newNotes & "' , '" & UserID & "')"
    Debug.Print strSQL
    CurrentDb.Execute strSQL
        
    MsgBox ("Allocation has been entered.")
    
    Set rs = Nothing
End Sub
vba ms-access ms-access-2016
1个回答
1
投票

避免笨拙的 SQL 并使用 DAO 的强大功能来获得更简洁的代码:

Private Sub addAllocation_Click()

    Dim strSQL  As String
    Dim user_id As String
    Dim rs      As DAO.Recordset

    If IsNull(Me!newEffectiveDate.Value) Or IsNull(Me!newAmount.Value) Then
        MsgBox "Please complete all required fields."
        Exit Sub
    End If
    
    UserID = Left(Environ("USERNAME"), 15)

    strSQL = "Select * From Participant_Allocation"
    Set rs = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset, dbAppendOnly)
    rs.AddNew
        rs!Transaction_ID.Value = Me!txtTransactionID.Value
        rs!Participant_ID.Value = Me!cmbParticipantID.Column(3)
        rs!Loan_ID.Value = Me!cmbLoan.Value
        rs!Allocation_Amount.Value =Me!newAmount.Value
        rs![Effective Date].Value = Me!newEffectiveDate.Value
        rs!Notes.Value = Me!newNotes.Value
        rs!user_ID.Value = UserID
    rs.Update
    rs.Close  

    MsgBox "Allocation has been entered."

    Set rs = Nothing

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