Reputation: 29
I currently am running a form linked to a table where one of the controls displayed in the form is dependent on another another control. Specifically, it is a field called Machine Excavation that needs to be the remaining percentage of a user inputted percentage in the field Hand Excavation. These fields pertain to a specific record chosen specified from another control in the form called Excavation Type. For example if I input 30% into Hand Excavation then Machine Excavation needs to be 70%. I've created a code that will use a RunSQL method in VBA to store this in the underlying table upon execution of an AfterUpdate event in the Hand Excavation control:
Private Sub Text_HandExcvPerc_AfterUpdate()
DoCmd.RunSQL ("UPDATE tbl-ExcavationType SET [Machine Excavation] = 1 - [Hand Excavation] WHERE [Excavation Type] = Text_ExcvType.Value;") End Sub
tbl-ExcavationType is the table linked to the form and Text_ExcvType.Value is the textbox control that contains the current record identifier. Can someone comment on the syntax of my DoCmd.RunSQL? I keep getting an error.
Upvotes: 1
Views: 873
Reputation: 2906
DoCmd.RunSQL ("UPDATE [tbl-ExcavationType] SET [Machine Excavation] = " & _
"1 - [Hand Excavation] WHERE [Excavation Type] = """ & Text_ExcvType.Value & """;")
Notice that there are three quotation marks surrounding the text box value. Access uses double quotes instead of single quotes for strings. Because you are entering it in a string, you have to use two double quotes to indicate the single double quote for your string, then another one to break the string to concatenate your value. What the system sees will be effectively this:
UPDATE [tbl-ExcavationType] SET [Machine Excavation] = 1 - [Hand Excavation] WHERE [Excavation Type] = "My Data Value";
Upvotes: 1
Reputation: 23994
You have several issues:
-
.'
) or double quotes ("
).Text_ExcvType.Value
rather than the string "Text_ExcvType.Value"
into the query.I have tested that the following works:
Private Sub Text_HandExcvPerc_AfterUpdate()
DoCmd.RunSQL "UPDATE [tbl-ExcavationType] SET [Machine Excavation] = 1 - [Hand Excavation] WHERE [Excavation Type] = '" & Text_ExcvType.Value "';"
End Sub
Upvotes: 2
Reputation: 4714
What you have here appears to be a calculated field: ie [Machine Excavation] is always 1 - [Hand Excavation] so I don't see why you need to store it. That said you need to replace the words "Text_ExcvType.Value" with the actual value in the control called Text_ExcvType and it can't do that while it's inside speech marks. Try
dim strsql as string
strsql = "UPDATE tbl-ExcavationType SET [Machine Excavation] = "
strsql = strsql & "1 - [Hand Excavation] WHERE [Excavation Type] = '"
strsql = strsql & Text_ExcvType.Value & "';"
DoCmd.RunSQL strsql
This allows access to first evaluate Text_ExcvType.Value, put the result into the string and then execute the sql Doing it this way also allows you to watch the string build in debug to work out where it's going wrong
Upvotes: 0