通过VBA / SQL从Excel应用程序更新Microsoft Access表字段

时间:2015-05-31 19:26:30

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

我已成功连接到数据库,但问题是它何时更新表字段。它更新表中的整个字段,而不是搜索ID号,只更新该特定的Time_out字段。这是下面的代码,我必须遗漏一些东西,希望我忽略了一些简单的东西。

Sub UpdateAccessDatabase()

    Dim accApp As Object
    Dim SQL As String
    Dim id

    id = frm2.lb.List(txt)

    SQL = "UPDATE [Table3] SET [Table3].Time_out = " & "Now()" & " WHERE "
    SQL = SQL & "((([Table3].ID)=id));"

    Set accApp = CreateObject("Access.Application")

    With accApp
        .OpenCurrentDatabase "C:\Signin-Database\DATABASE\Visitor_Info.accdb"
        .DoCmd.RunSQL SQL
        .Quit
    End With

     Set accApp = Nothing

 End Sub

3 个答案:

答案 0 :(得分:2)

如果id是整数/长,您应该按如下方式修改查询:

SQL="UPDATE [Table3] SET [Table3].Time_out=#" & Now() & "# WHERE [Table3].ID=" & id;

如果id是文本,您应该按如下方式修改查询:

SQL="UPDATE [Table3] SET [Table3].Time_out=#" & Now() & "# WHERE [Table3].ID='" & id &"'";

希望这可能会有所帮助。

答案 1 :(得分:-1)

以下是工作守则:

Sub UpdateAccessDatabase()
Dim accApp As Object
Dim SQL As String
Dim id
id = frm2.lb.List(txt)
***'modified lines below***
SQL = "UPDATE [Table3] SET [Table3].Time_out = " & "Now()" & " WHERE "
SQL = SQL & "((([Table3].ID)=" & id & "));"

Set accApp = CreateObject("Access.Application")
With accApp
.OpenCurrentDatabase "C:\Signin-Database\DATABASE\Visitor_Info.accdb"
.DoCmd.RunSQL SQL
.Quit
 End With
 Set accApp = Nothing

 End Sub

答案 2 :(得分:-1)

@alex

我能够将查询修改为上面提到的SQL语句

我确实要从声明中删除一些(#,')以使其正常工作,但这更清晰

所以这是下面的另一个工作示例

`Sub UpdateAccessDatabase()
 Dim accApp As Object
 Dim SQL As String
 Dim id
 id = frm2.lb.List(txt)
 ***'modified lines below***
 SQL = "UPDATE [Table3] SET [Table3].Time_out= " & "Now()" & " WHERE [Table3].ID=" & id & ""


 Set accApp = CreateObject("Access.Application")
 With accApp
 .OpenCurrentDatabase "C:\Signin-Database\DATABASE\Visitor_Info.accdb"
 .DoCmd.RunSQL SQL
 .Quit
  End With
  Set accApp = Nothing

  End Sub`