使用Microsoft Excel错误中的VBA将数据从Excel导出到Access

时间:2016-09-22 15:42:07

标签: sql vba excel-vba ms-access-2010 excel

我目前正在使用Excel VBA制作服务系统应用程序。我有一个用户表单来获取输入,我想将导入数据保存到几个Microsoft Access表中。

我正在尝试从userform中提取数据并将其输入到访问表中当我运行此代码时出现语法错误。我需要你的帮助。

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

1 个答案:

答案 0 :(得分:0)

@Comintern所说的可以用这种方式解释。
用转义双引号或单引号

包装字符串变量

喜欢这个

  stSQL = "INSERT INTO Client (FullName, Address) " & _
          "Values (""" & Name & """, """ & Address & """)"

或者

  stSQL = "INSERT INTO Client (FullName, Address) " & _
          "Values ('" & Name & "', '" & Address & "')"

如旁注,

  

最好改变你的姓名"变量到某事   否则,因为这是VB / VBA中的保留字