问题
I'm trying to close out a record, where I have a True/False column inside a table. Code below, I keep getting a compile error expected end of statement. What am I missing? It will only be one record that is True at any given time.
If Me.butCompleteFlight.Value = True Then
UPDATE tblFlightRecords SET strWorkingRecord = FALSE WHERE strWorkingRecord = TRUE
回答1:
You can't mix SQL code and VBA code like that.
You can execute the update statement with the method DoCmd.RunSQL:
If Me.butCompleteFlight.Value = True Then
Dim SQL As String
SQL = "UPDATE tblFlightRecords SET strWorkingRecord = FALSE WHERE strWorkingRecord = TRUE"
DoCmd.RunSQL SQL
End If
回答2:
Generally, in no application layer language (from Java to Python to VBA) can you submit an SQL query by itself on a separate line. SQL is a special-purpose, separate language compared to a general-purpose language. Hence, it is not recognized in app layers.
You must invoke the SQL statement with an interface or API object. In MS Access VBA, there are many ways to run action queries, some of which support parameterization.
DoCmd Interface
DoCmd.OpenQuery (requires a saved query in advance)
DoCmd.RunSQL (runs a string query)
DAO API
QueryDef.Execute (requires a saved or temporary query and supports parameterization)
Database.Execute (runs a string or saved query)
ADO API
Connection.Execute (runs a string or stored query)
Command.Execute (runs a string or stored query, supports parameterization)
Do note: VBA is not the only way to connect to MS Access databases. Java, Python, C#, and still others can as well but you must adhere to the chosen SQL API, module, or library. None of which allows SQL to be run by itself on a separate line.
来源:https://stackoverflow.com/questions/59492375/how-to-update-a-record-in-a-table-via-a-sql-command-within-an-if-statement