如何使用VBA将Access表单中的数据插入到sql表中?

时间:2015-09-16 15:11:47

标签: sql vba ms-access

这就是我所拥有的,我尝试从Access表单中获取字段(数据来自一个链接的sql表)并将它们插入到另一个链接的sql表中:

StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
          VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", " Me.email & ")
DoCmd.RunSQL StrSQL

但我收到此错误

Compile error: Sub or Function not defined 

3 个答案:

答案 0 :(得分:3)

我认为你只是缺少一些双引号:

StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
"VALUES(" & Me.StatusID & ", " Me.TravellerUFID & ", " Me.SubmitterUFID & ", """ & Me.email & """)"
DoCmd.RunSQL StrSQL

您可以尝试打印StrSQL的内容并在运行之前检查查询:

Debug.Print StrSQL

但我不想创建具有连接值的SQL字符串(如果Me.StravellerUFID包含双引号会怎么样?)

我建议您使用DAO插入数据:

Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("dbo_Expense_Projection")
rs.AddNew
rs!StatusID = Me.StatusID
rs!TravellerUFID = Me.TravellerUFID
' ...other fields
rs.Update
rs.Close

答案 1 :(得分:0)

SQL-String中还缺少一些&符号:

StrSQL = "INSERT INTO [dbo_Expense_Projection] ([StatusID],[TravellerUFID],[Email]) " & _
          "VALUES(" & Me!StatusID & ", " & Me!TravellerUFID & ", " & Me!SubmitterUFID & ", """ & Me!email & """)"

而且我认为你应该在" Me"之间使用感叹号。和fieldname。但我不想与这里的专家争论......;)

答案 2 :(得分:0)

以下是最终工作的内容:

Dim StrSQL As String

StrSQL = "INSERT INTO dbo_Expense_Projection (StatusID,TravellerUFID,Email) 
          VALUES('" & Form!StatusID & "','" & Form!TravellerUFID & "','" & Form!Email & "')"

DoCmd.SetWarnings False
DoCmd.RunSQL StrSQL
DoCmd.SetWarnings True