I'm currently making a service system application using Excel VBA. I have a userform to get the input and I would like to save the import data into a few Microsoft Access tables.
I am trying to pull the data from the userform and enter it into the access table When I run this code have a Syntax error. Please i need your help.
Public Sub AddDatabaseEntry()
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim stDB As String, stSQL As String, stProvider As String
Dim Name As String
Dim Address As String
Name = TextBox1
Address = TextBox2
stDB = "Data Source= " & ThisWorkbook.Path & "\SERVDB.accdb"
stProvider = "Microsoft.ACE.OLEDB.12.0"
'Opening connection to database
With cn
.ConnectionString = stDB
.Provider = stProvider
.Open
End With
'SQL Statement of what I want from the database
stSQL = "INSERT INTO Client (FullName, Address) " & _
"Values (" & Name & ", " & Address & ")"
cn.Execute stSQL
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
Private Sub CommandButton2_Click()
AddDatabaseEntry
End Sub
What @Comintern says can be explained this way.
Wrap your string variables in escaped double quotes or single quotes
Like this
stSQL = "INSERT INTO Client (FullName, Address) " & _
"Values (""" & Name & """, """ & Address & """)"
Or this
stSQL = "INSERT INTO Client (FullName, Address) " & _
"Values ('" & Name & "', '" & Address & "')"
As as side note,
it's highly advisable to change your "NAME" variable to something else, as that is a reserved word in VB/VBA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.