插入语句VBA

时间:2015-10-19 00:34:08

标签: vba access-vba ms-access-2013

大家好我在VBA中使用Access 2013进行编码我用两种不同的方式编写了代码并且不断出现语法错误。这是我的代码。

Private Sub cmdAdd_Click()
      CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name, 
phone, email, EmergencyContact, EmergencyContact) " & _
" VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" & Me.txtName & "','"  
& Me.txtEmail & "','" & Me.txtPhone & "','" & Me.txtEmergencyContact & "','"
& Me.EmergencyNumber & "','" & Me.txtRegNumber & "')"

'clear form
cmdClear_Click
'refresh data in list on form
frmStudentSub.Form.Requery
End Sub

OR

'when we click on button Add there are two options
 '1. for insert
 '2. for update
 If Me.txtRegNumber & "" = "" Then
    'this is for insert new
    'add data to table
    CurrentDb.Execute "INSERT INTO GroupVolunteers(Group, Leader, Name, 
   phone, email, EmergencyContact, EmergencyContact) " & _
            " VALUES(" & Me.txtGroup & "','" & Me.cboLeader & "','" &    
  Me.txtName & "','" & _
            Me.txtEmail & "','" & Me.txtPhone & "','" &   
    Me.txtEmergencyContact & "','" & Me.EmergencyNumber & "','" &_  
   Me.txtRegNumber & "')"
Else
'otherwise (Tag of txtID store the id of student to be modified)
 CurrentDb.Execute "UPDATE GroupVolunteers " & _
      " SET Group=" & Me.txtGroup & _
            ", leader='" & Me.cboLeader & "'" & _
    ", name='" & Me.txtName & "'" & _
            ", email='" & Me.txtEmail & "'" & _
    ", phone='" & Me.txtPhone & "'" & _
    ", EmergencyContact='" & Me.txtEmergencyContact & "'" & _
            ", EmergencyNumber='" & Me.txtEmergencyNumber & "'" & _
            ", NumberVolunteers ='" & Me.txtNumberVolunteers & "'" & _
            " WHERE RegNumber = " & Me.txtRegNumber.Tag

1 个答案:

答案 0 :(得分:3)

" VALUES(" & Me.txtGroup & "', ...

想一想你的陈述会如何结束:

VALUES(<Me.txtGroup>', ...

换句话说,您要么缺少字符类型列的开头引号,要么对数字类型列有太多引号。它应该是以下之一:

" VALUES('" & Me.txtGroup & "', ...  // for character-type column
" VALUES(" & Me.txtGroup & ", ...    // for numeric-type column

这应修复两个代码块中的insert,您可能还想检查第二个代码块中的update。它在group列上没有引号,如果它是数字类型就没关系,但如果它是字符类型则可能没有。