VBA SQL update/insert 到本地 table 使用表单中的值

VBA SQL update/insert to local table using values from form

我正在尝试使用用户在表单中填充的值来更新存储在访问中的本地 table 中的一行(或者如果该 ID 尚不存在,则插入一个新行)。我正在使用 SQL 在 VBA 中编写它。这是代码:

Public Function update_table()

Dim strSQL As String

strSQL = "IF NOT EXISTS (SELECT * FROM table1 WHERE (id1 = [Forms]![Study Info Cleaned]![Text156] AND id2 = [Forms]![Study Info Cleaned]![Text158]))" & _
    "INSERT INTO table1 ( id1, id2, id3, id4, id5 )" & _
    "VALUES ([Forms]![Study Info Cleaned]![Text156]," & _
        "[Forms]![Study Info Cleaned]![Text158]," & _
        "[Forms]![Study Info Cleaned]![Text160]," & _
        "[Forms]![Study Info Cleaned]![Text201]," & _
        "[Forms]![Study Info Cleaned]![Text166])" & _
"Else" & _
    "Update table1" & _
    "SET id4 = [Forms]![Study Info Cleaned]![Text201], id5 = [Forms]![Study Info Cleaned]![Text166]" & _
    "WHERE (id1 = [Forms]![Study Info Cleaned]![Text156] AND id2 = [Forms]![Study Info Cleaned]![Text158])"


DoCmd.RunSQL (stringSQL)


End Function

代码returns错误信息如下:

运行-时间错误‘3129’,无效的SQL语句;预期 'DELETE'、'INSERT'、'PROCEDURE'、'SELECT' 或 'UPDATE'.

MS Access SQL 不支持 if 语句,仅支持 iif 语句。

因此,您可能需要在 VBA 内实现逻辑,例如:

Public Function update_table()
    Dim strSQL As String

    If DCount("*","table1","id1 = [Forms]![Study Info Cleaned]![Text156] AND id2 = [Forms]![Study Info Cleaned]![Text158]") = 0 Then
        strSQL = _
        "INSERT INTO table1 ( id1, id2, id3, id4, id5 ) " & _
        "VALUES ([Forms]![Study Info Cleaned]![Text156]," & _
        "[Forms]![Study Info Cleaned]![Text158]," & _
        "[Forms]![Study Info Cleaned]![Text160]," & _
        "[Forms]![Study Info Cleaned]![Text201]," & _
        "[Forms]![Study Info Cleaned]![Text166])"
    Else
        strSQL = _
        "UPDATE table1 " & _
        "SET id4 = [Forms]![Study Info Cleaned]![Text201], id5 = [Forms]![Study Info Cleaned]![Text166] " & _
        "WHERE (id1 = [Forms]![Study Info Cleaned]![Text156] AND id2 = [Forms]![Study Info Cleaned]![Text158])"
    End If
    DoCmd.RunSQL strSQL
End Function

还有一些其他问题:

  • stringSQL 是一个拼写错误,因为您最初将变量定义为 strSQL.
  • DoCmd.RunSQL (stringSQL) 括号不应包含参数,因为该表达式不是另一个表达式的一部分。