SQL在vba代码中插入语法错误

时间:2014-02-13 19:35:47

标签: sql vba ms-access insert

有人可以帮我正确格式化这个字符串,以便在执行按钮命令时执行我的SQL代码吗?我是视觉基础的新手,不知道我在哪里弄乱这个部分,或者我甚至可以在我的查询中包含Access控件。

以下是我试图执行的代码:

Private Sub new_record_btn_Click()
Dim conn As ADODB.Connection
Dim sSQL As String

Set conn = CurrentProject.Connection

RunCommand acCmdSaveRecord

sSQL = "INSERT INTO tblHydro( [Mine ID], [Facility], [Status], [Commodity], [Is   Mine Currently Below Water Table (3/10/07)?] ) SELECT tblMine.MineID, tblMine.MineName, tblMine.Status, tblMineAcreage.CommodityType, tblPermits.GWImpact FROM (tblMine INNER JOIN tblPermits ON tblMine.MineID = tblPermits.MineID) INNER JOIN tblMineAcreage ON (tblPermits.PermitID = tblMineAcreage.PermitID) AND (tblMine.MineID = tblMineAcreage.MineID) WHERE 'Forms!frmHydroNEW.MineID' = tblHydro.[Mine ID]"
conn.Execute sSQL
frmHydroSub.Requery
End Sub

我从上面的

中得到语法错误

我不确定这是否是解决这个问题的正确方法.... :(

非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:0)

你最好使用:

Set db = CurrentDB
db.Execute sSQL

所以

sSQL = "INSERT INTO tblHydro ( [Mine ID], [Facility], [Status], " _
& "[Commodity], [Is   Mine Currently Below Water Table (3/10/07)?] ) " _
& "SELECT tblMine.MineID, tblMine.MineName, tblMine.Status, " _
& "tblMineAcreage.CommodityType, tblPermits.GWImpact " _
& "FROM (tblMine INNER JOIN tblPermits ON tblMine.MineID = tblPermits.MineID) " _
& "INNER JOIN tblMineAcreage ON (tblPermits.PermitID = tblMineAcreage.PermitID) " _
& "AND (tblMine.MineID = tblMineAcreage.MineID) " _
& "WHERE tblHydro.[Mine ID]=" &  Forms!frmHydroNEW.MineID

''Or possibly Me.MineID, depending on where the code is running

db.Execute sSQL

但是,[Is Mine Currently Below Water Table (3/10/07)?]是一个非常奇怪的字段名称,如果它是一个参数,则需要更多工作。

在VBA中,表单不能以这种方式引用,它必须在引号之外,因此返回一个值,而不是对表单的引用。另请注意,表单必须打开。