【问题标题】:VBA SQL update/insert to local table using values from formVBA SQL 使用表单中的值更新/插入本地表
【发布时间】:2019-12-10 08:30:29
【问题描述】:

我正在尝试使用用户在表单中填充的值来更新存储在 access 中的本地表中的一行(或插入一个新行,如果该 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

代码返回以下错误信息:

运行时错误'3129',无效的SQL语句;预期为“DELETE”、“INSERT”、“PROCEDURE”、“SELECT”或“UPDATE”。

【问题讨论】:

    标签: sql vba forms ms-access upsert


    【解决方案1】:

    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) 括号不应围绕参数,因为表达式不是另一个表达式的一部分。

    【讨论】:

    • 这很好,谢谢。你介意详细说明关于括号的最后一个问题吗?如果表达式是嵌套的,你是否只围绕参数?
    • @RonanGarrison 不客气。 Here's the official explanation 关于何时在 VBA 中使用括号 - 我希望这会有所帮助。
    猜你喜欢
    • 2017-01-10
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    • 2022-11-11
    • 2018-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多