SQL statement in ms access db bringing up InputBox - sql

I have VBA for a form.
I'm trying to take the information in a textbox on the form and update a particular field in a table. (haven't figured out how to do that properly)
This line of code is my current try but I'm getting unexpected behavior
The program doesn't continue executing after this
If (Not IsNull([New_Value_Box].Value)) Then
DoCmd.RunSQL "Update [Export_NDC_Certification] Set " & [Field_List].Value & " = " & [New_Value_Box].Value & " WHERE SellerLoanIdentifier = " & Current_Loan
End If
it does however open an input box with the value of Current_Loan as the caption. It doesn't appear to do anything with the input and it doesn't execute any further code. I've used MsgBox's for debugging and its definitely coming from this line. This line was what I came across for taking a value and updating a particular table value with it. if this isn't the way to do it any push in the right direction would be appreciated. Thank you!

First, I would recommend using the Execute method (of either DAO.Database or DAO.QueryDef), instead of using DoCmd.RunSQL. This makes debugging a lot easier (here's a forum post with more information).
Also, since it seems that you need values in all your controls ([Field_List], [New_Value_Box], and Current_Loan), you should do a null check on all of those.
As noted by #HansUp, your actual SQL string is likely causing the issue, so you probably want to store that in a separate variable you can then output to the immediate window.
With all that being said, revised code might look something like this:
Dim db As DAO.Database, qdf As DAO.QueryDef
Dim strSQL As String
If _
IsNull([New_Value_Box].value) Or _
IsNull([Field_List].value) Or _
IsNull([Current_Loan].value) _
Then
' handle missing input
Else
' we know all required fields have values, so can proceed
strSQL = _
"UPDATE [Export_NDC_Certification " & _
"SET " & [Field_List].value & "=" & [New_Value_Box].value & " " & _
"WHERE SellerLoanIdentifier=" & Current_Loan
Debug.Print strSQL
Set db = CurrentDb
Set qdf = db.CreateQueryDef("")
qdf.SQL = strSQL
qdf.Execute dbFailOnError
End If
' clean up DAO objects
Set qdf = Nothing: Set qdf = Nothing: Set db = Nothing

Related

SQL statement returning "could not find file" while executing

In my code, I am trying to use an input box to hold a user inputted value as a string, then use SQL to then update a field based on that.
My code is:
Dim strinput
Dim strsql
Call CreateRevisions
strinput = InputBox(prompt:="Name of revision")
If Not IsNull(strinput) Then
'DoCmd.SetWarnings False
strsql = " UPDATE tblJobDetails.RevisionName"
strsql = strsql & " SET tblJobDetails.RevisionName = '" & strinput & "'"
strsql = strsql & " WHERE (((tblJobDetails.JobID)=[Forms]![JobQuote]![JobID]));"
'DoCmd.RunSQL strsql
CurrentDb.Execute strsql
'docmd.setwarnings true
End If
End Sub
When it runs, I get the prompt that fields are about to be updated, then the input box appears and allows me to enter something. I checked the value of strinput and it is holding the value correctly, but when I try to actually execute the SQL statement I can an interesting error I haven't run into before.
The error is :
Run-time error '3024':
Could not find file 'C\....
I have run various statements like this before with no problem. This is the first time I have tried using the input box however. What is causing that error?
I have tried changing it to docmd as well as adding in debug.print, but it still results in the same error.

Update Access Query using VBA

I'm trying to update an access query using VBA and changing the Like criteria in the SQL statement, but although I know that SQL code works, when running with VBA it continues to return the same information.
My code is below:
Function FTPCost()
Dim database As DAO.database
Dim query As DAO.QueryDef
Dim strSQL As String
Set database = CurrentDb
Set query = database.QueryDefs("ftp_for_a_part_Query")
strSQL = "SELECT ftp_for_a_part.PART, ftp_for_a_part.STD_TOT, ftp_for_a_part.DATE " & _
"FROM ftp_for_a_part " & _
"WHERE (((ftp_for_a_part.PART) Like '******')) " & _
"ORDER BY ftp_for_a_part.DATE DESC;"
'MsgBox strSQL
query.SQL = strSQL
DoCmd.OpenQuery "ftp_for_a_part_Query"
Set query = Nothing
Set database = Nothing
End Function
Solved my problem. The fact the SQL code was not updating the Query was being caused by the query window being open. I did not understand that for the query to run the Query window must be closed.

VBA Append Query Using Access

I am attempting to add a button to a form to add the contents of the form as a new line in my table. I have written this line of code before, but this time it isn't working.
My form contains text and integers. 3 boxes on the form are auto-populated when the form loads. (Will the auto populated boxes change anything?)
Instead of trying to make the whole string work, I have reduced my code to just add one box (one of the auto-populated boxes). I get a Rune-time error '438': Object doesn't support this property or method.
I've tried googling the error, but I cannot find anything that applies.
The code is as follows:
Dim strInsert As String
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values(" & Me.TxtIdKey & ")"
Debug.Print strInsert
CurrentProject.Execute strInsert, dbFailOnError
MsgBox ("Entry Added")
When I look at the debug screen it shows the following:
INSERT INTO NLog(IDKEY) Values(OH08801405)
I am so frustrated! I am still very new to this, and I feel totally out of my element.
You could execute your INSERT statement with ADO like this ...
CurrentProject.Connection.Execute strInsert
Note CurrentProject.Connection.Execute, not CurrentProject.Execute, and don't include the DAO constant dbFailOnError when executing from ADO.
Or with DAO like this ...
CurrentDb.Execute strInsert, dbFailOnError
Also, you were attempting to insert a text value into the IDKEY field. Assuming text is the correct datatype for that field, add quotes around the value you're inserting ...
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values('" & Me.TxtIdKey & "')"
Then you should see Debug.Print output similar to this ...
INSERT INTO NLog(IDKEY) Values('OH08801405')
Without quotes surrounding OH08801405, the db engine will not understand it is supposed to be a string value it should insert, and instead will assume it is a parameter for which you haven't supplied a value.
I have to assume that the error message is happening at CurrentProject.Execute strInsert, dbFailOnError since your debug actually shows something.
You will need to set up a connection to your database and use db.Execute strInsert, dbFailOnError.
You declare a connection like this:
Dim db As DAO.Database
Set db = CurrentDb
So you should end up with something like:
Dim strInsert As String
Dim db As DAO.Database
strInsert = "INSERT INTO NLog(IDKEY) " & _
" Values(" & Me.TxtIdKey & ")"
Debug.Print strInsert
Set db = CurrentDb
db.Execute strInsert, dbFailOnError
MsgBox ("Entry Added")

ACCESS/SQL - Too Few Parameters

I am using the code below to create a new record in the "transactions table" the second line of the insert statement is throwing an error: Too few parameters. I have double checked and all of the field names are correct. What else could cause this type of error?
' Modify this line to include the path to Northwind
' on your computer.
Set dbs = CurrentDb
Dim vblCustomerID As String
Dim vblMealType As String
Dim Charge As Currency
Dim vblDate As String
vblDate = Format(Date, "yyyy-mm-dd")
txtCustomerID.SetFocus
vblCustomerID = txtCustomerID.Text
txtMealType.SetFocus
vblMealType = txtMealType.Text
txtCharge.SetFocus
vblCharge = txtCharge.Text
dbs.Execute "INSERT INTO dbo_Transactions" _
& "(CustomerID, MealID, TransactionAmount, TransactionDate) VALUES " _
& "(" & vblCustomerID & ", " & vblMealType & ", " & vblCharge & ", " & vblDate & ");"
dbs.Close
As others have suggested, using a parameterized query is a much better way of doing what you're attempting to do. Try something like this:
Dim qdf As DAO.QueryDef
Set qdf = dbs.CreateQueryDef("", _
"PARAMETERS prmCustomerID Long, prmMealID Long, prmTransactionAmount Currency, prmTransactionDate DateTime;" & _
"INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _
"VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate]) ")
qdf!prmCustomerID = txtCustomerID.Value
qdf!prmMealID = txtMealType.Value
qdf!prmTransactionAmount = txtCharge.Value
qdf!prmTransactionDate = Date()
qdf.Execute dbFailOnError
Set qdf = nothing
Do any of the text fields you're loading into your vbl fields contain special characters like these?
, ' "
All of those in a text field in a perfectly good SQL Insert command could screw things up, I bet that's what happening here.
It would be better if you actually use parameters here to, rather than loading the text in textboxes directly into your SQL queries, since you're opening yourself up to SQL Injections. What if someone types
"; Drop Table dbo_Transactions;
in one of your textboxes and you run this query? Your database is then totally screwed up because someone just deleted one of your tables.
A few links to info on using Parameters to prevent this issue, which I'll bet will also fix the too few parameters issue you're having.
http://forums.asp.net/t/886691.aspx
http://sqlmag.com/blog/t-sql-parameters-and-variables-basics-and-best-practices

Inserting into a different table from a form

I am trying to make an event when iputing data in a form on access, after the text box looses focus, if the box is not null I want the ID and the value to get stored into another table. After trying with the code below I get "Runtime error 3061 Too few parameters Expected 1". I have checked in debug mode and the values are getting carried over and brought to the string.
Private Sub Consolidate_LostFocus()
Dim queryString As String
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value & ", " & [Consolidate].Value & ")"
If Consolidate.Text <> vbNullString Then
CurrentDb.Execute (queryString)
End If
End Sub
If either the # or the Notes fields in ReportMasterTable is text data type, you must add quotes around the values you attempt to INSERT.
For example, if both fields are text type:
queryString = "INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES ('" & [#].Value & "', '" & [Consolidate].Value & "')"
The situation will be more complicated if either [#].Value or [Consolidate].Value contains a single quote. You could double up the single quotes within the inserted values. However it might be easier to just switch to a parameterized query ... the quoting problem would go away.
Dim db As DAO.database
Dim qdf As DAO.QueryDef
Dim strInsert As String
strInsert = "PARAMETERS hash_sign Text (255), note_value Text (255);" & vbCrLf & _
"INSERT INTO [ReportMasterTable]([#], [Notes])" & vbCrLf & _
"VALUES (hash_sign, note_value)"
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", strInsert)
qdf.Parameters("hash_sign").value = Me.[#]
qdf.Parameters("note_value").value = Me.[consolidate]
qdf.Execute dbFailOnError
Set qdf = Nothing
Set db = Nothing
You could also save the SQL statement as a named query and open and execute that instead of rebuilding the statement every time your procedure runs.
Is there any reason why you do not wish ti bind the form to the ReportMasterTable?
If you really have a control and field called #, you are facing a world of trouble.
If you have bound the form to ReportMasterTable and are also updating in a query, you are going to run into problems.
The lost focus event is a very bad event to choose, any time anyone tabs through the form, the code will run. After update would be better.
You are updating a text data type, but you have not used quotes.
"INSERT INTO [ReportMasterTable]([#], [Notes]) VALUES(" & [#].Value _
& ", '" & [Consolidate].Value & "')"