MS Access Too Few Parameters: Expected 1 - ms-access

So I'm trying to take data from a table, set that piece of data to a variable, and add that variable into a new table.
This is the code to access the last name of the person I'm searching for. I'm almost 100% sure this part works.
Dim db As Database
Dim Lrs As DAO.Recordset
Dim LSQL As String
Set db = CurrentDb()
Set Lrs = db.OpenRecordset("Select [LastName]" & _
"From ['Chromebook Registration Form]" & _
"Where [InventoryNumber] = 1")
dbLastName = Lrs("LastName")
In debug mode, it shows that the variable "dbLastName" contains the string that I want.
However, when I run the following code (to add the information into a new table), I get a 3061 Run-time error code. Too few parameters: expected 1.
The debugger says the problem is in the last line. I assume it is a problem with "dbLastName". The timestamp thing works fine.
CurrentDb.Execute " INSERT INTO TempReg " _
& "([Timestamp], LName, FName, Grade, InventoryNumber, SerialNumber, MacAddress, PaidIn, CheckNum) VALUES " _
& "(Now, dbLastName, 'test', 'test', 'test', 'test', 'test', 'test', 'test');"
Thank you!

You can't just embed a string variable into SQL. Instead of
(Now, dbLastName, 'test ...
You need
(Now(), '" & dbLastName & "', 'test' …
In addition you need to make sure your variable will never include the single quote character, otherwise you have to also take that into account by doubling it.

Related

How to set TextBox Comment Value Input as Table Data Insert on MS Access VBA

I have a main "final table" being updated through VBA based on many inputs of a Form and other tables data. I am trying to callout a TextBox object value that exists in a form to the VBA code so user can add a comment to all the data being inserted into the final table.
Dim strComment As String
strComment = TextBox_Comment.Value
strSQL = "INSERT INTO Main_Table (Period, Monthp, Order, Comment)"
strSQL = strSQL & "SELECT ""Weekly"" AS Period, [001_SelectedMonth].Monthp, [001_OrderTable].Order, strComment AS Comment FROM 001_SelectedMonth, 001_OrderTable;"
CurrentDb.Execute strSQL, dbFailOnError
The code works fine when I remove both the "Comment" from the Main Table insertion points and the "strComment AS Comment" part of the code. Otherwise I get the Run-Time Error '3061', Too few parameters. Expected 1.
Question: is there a way for me to callout the text box value to be inserted in the database as a field data for all the data being added or should I use another method to do this?
Example of the final table:
You need a space and proper concatenation:
strSQL = "INSERT INTO Main_Table ([Period], Monthp, [Order], [Comment]) "
strSQL = strSQL & "SELECT 'Weekly' AS [Period], [001_SelectedMonth].Monthp, [001_OrderTable].Order, '" & strComment & "' AS [Comment] FROM 001_SelectedMonth, 001_OrderTable;"
That said, use parameters to avoid the concatenation.

VBA Access: No value given for one or more required parameters

I know, there are lots of answers out there for this problem which should be trivial, but I did not find the right one. Here is my problem:
I open a record set with the following select statement:
SELECT twinecellar.produktnavn, twinecellar.land,
twinecellar.produkttype, twinecellar.år,
twinecellar.antall, twinecellar.poeng,
twinecellar.Picture, twinecellar.KR,
twinecellar.Poengsum, twinecellar.Sum
FROM twinecellar
WHERE (((twinecellar.land)=forms!fmainview!list13)
And ((twinecellar.produkttype)=forms!fmainview!list15))
ORDER BY twinecellar.poeng;
In the immidiate window I see that list 13 contains "france" and list 15 contains "red"
When I create a new Query with this statement, it's working, however, on the rst.Open gsStrQuery I get this error. gsStrQuery contains the select string.
Here is the code:
Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset
Set conn = CurrentProject.Connection
Set rst = New ADODB.Recordset
rst.CursorType = adOpenDynamic
rst.ActiveConnection = conn
rst.Open gsStrQuery
Anybody out there with a good idea about this issue?
When you build your SQL string, concatenate the "parameters" values into the string.
gsStrQuery = "SELECT twinecellar.produktnavn, twinecellar.land, " & _
"twinecellar.produkttype, twinecellar.år, " & _
"twinecellar.antall, twinecellar.poeng, " & _
"twinecellar.Picture, twinecellar.KR, " & _
"twinecellar.Poengsum, twinecellar.Sum " & _
"FROM twinecellar " & _
"WHERE (((twinecellar.land)= '" & forms!fmainview!list13 & "') " & _
"And ((twinecellar.produkttype)= '" & forms!fmainview!list15 & "')) " & _
"ORDER BY twinecellar.poeng;"
That way your parameter values are hard coded into the string before you try to open the query.
(Also note: I added single quotes around your parameters to indicate they are strings.)
(Also also note: & _ is a line continuation for VBA so your SQL string concatenates properly. This allows you have a readable SQL code that's nicely indented.)
________________________________
There is also a way to use your current gsStrQuery and assign parameters values to the ADO recordset. (But I find the above Replacement method much easier to read when going back to review the code. The only drawback is you have to rebuild your SQL string each time your parameters change. But that overhead is minimal for non complicated queries.)
However, if you really want to use ADO parameters, you can find a useful description here.
Hope that helps :)

Insert statement in access gives error

I have been working on creating an extremely simple database with only 4 tables and only a few pieces of information per column. One of my tables is called "Customer" and inside of this table there or 4 columns for information.
I have a button on my "AddCustomerForm" that runs the following command
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer(Customer ID, Email, Identifier) " & _
= VALUES(Customer ID, Email, Identifier)
End Sub
My Add customer form looks like this:
Could someone please point out what I am messing up? The error I receive is :
Syntax error.
There's a few issues I see - is [Customer ID] an autonumber field? If so don't include it.
Also - if you're running a Manual Insert I assume your form is NOT bound to your table, though I begin to wonder why Customer ID is shown on the form as being editable?
Finally it looks like Location is a numeric ID belonging to ID field of the Location dropdown that fills in the Business ID field
This will help you debug your SQL and show us what's wrong
Add it to your button and show us the value shown in Immediate Window when the code halts
Dim strSQL as string
strSQL = "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """,""" & Me.[Identifier] & """)"
Debug.print strSQL
CurrentDb.Execute strSQL
If Customer ID is AutoNumber try this instead (assuming form is UNBOUND) and Location is ID value of first column of dropdown
Dim strSQL as string
strSQL = "INSERT INTO Customer (Email, Identifier) VALUES (" _
& me.[Customer ID] & ",""" & Me.[Email] & """, & Me.[Identifier] & ")"
Debug.print strSQL
CurrentDb.Execute strSQL
Private Sub cmdadd_Click()
CurrentDb.Execute "INSERT INTO Customer ([Customer ID], Email, Identifier) VALUES([Forms]![MyFormName]![CustomerIDTextboxName], [Forms]![MyFormName]![EmailtextboxName], [Forms]![MyFormName]![IdentifierTextboxName]);"
End Sub
Access requires brackets around any field name with a space. I also deleted the = before VALUES and changed the values to reference your form controls, which you will have to name appropriately. You also need a semi-colon to complete the statement and need to close your double-quotes.
This page might help with syntax.

saving data from form to table in access

I have a form, and I want to fill it, and then save some of the fields into an existing table called Order.
I'm trying to do this with this line of code:
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES (' " & Me.order & " ')"
I have also tried it like this
CurrentDb.Execute "INSERT INTO Order (OrderNumber)" & " VALUES ( " & Me.order & " )"
but it doesn't seem to make a difference. I keep getting the following error:
run-time error '3134': syntax error in INSERT INTO statement.
what am I doing wrong?
Order is a reserved word. If you must keep that as the table name, bracket it to avoid confusing the db engine.
Dim strInsert As String
strInsert = "INSERT INTO [Order] (OrderNumber) VALUES ('" & Me.order & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailOnError
If OrderNumber is numeric data type instead of text, discard those single quotes from the INSERT statement.
Store your statement in a string variable. Then use Debug.Print to examine the completed statement you're asking the engine to execute. You can view the Debug.Print output in the Immediate window. Go there with Ctrl+g Copy the statement and paste it into SQL View of a new Access query for troubleshooting.

How can I check for null values in Access?

I am new to Access. I have a table full of records. I want to write a function to check if any id is null or empty. If so, I want to update it with xxxxx.
The check for id must be run through all tables in a database.
Can anyone provide some sample code?
I'm not sure if you are going to be able to find all tables in the database with Access SQL. Instead, you might want to write up some VBA to loop through the tables and generate some SQL for each table. Something along the lines of:
update TABLE set FIELD = 'xxxxxx' where ID is null
Check out the Nz() function. It leaves fields unaltered unless they're null, when it replaces them by whatever you specify.
For reasonable numbers and sizes of tables, it can be quicker to just
open them
sort by each field in turn
inspect for null values and replace manually
It's good practice to find out where the nulls are coming from and stop them - give fields default values, use Nz() on inputs. And have your code handle any nulls that slip through the net.
I'm calling it the UpdateFieldWhereNull Function, and shown is a Subroutine which calls it (adapted from http://www.aislebyaisle.com/access/vba_backend_code.htm)
It updates all tables in the DbPath parameter (not tested, handle with care):
Function UpdateFieldWhereNull(DbPath As String, fieldName as String, newFieldValue as String) As Boolean
'This links to all the tables that reside in DbPath,
' whether or not they already reside in this database.
'This works when linking to an Access .mdb file, not to ODBC.
'This keeps the same table name on the front end as on the back end.
Dim rs As Recordset
On Error Resume Next
'get tables in back end database
Set rs = CurrentDb.OpenRecordset("SELECT Name " & _
"FROM MSysObjects IN '" & DbPath & "' " & _
"WHERE Type=1 AND Flags=0")
If Err <> 0 Then Exit Function
'update field in tables
While Not rs.EOF
If DbPath <> Nz(DLookup("Database", "MSysObjects", "Name='" & rs!Name & "' And Type=6")) Then
'UPDATE the field with new value if null
DoCmd.RunSQL "UPDATE " & acTable & " SET [" & fieldName & "] = '" & newFieldValue & "' WHERE [" & fieldName & "] IS NULL"
End If
rs.MoveNext
Wend
rs.Close
UpdateFieldWhereNull = True
End Function
Sub CallUpdateFieldWhereNull()
Dim Result As Boolean
'Sample call:
Result = UpdateFieldWhereNull("C:\Program Files\Microsoft Office\Office\Samples\Northwind.mdb", "ID", "xxxxxx")
Debug.Print Result
End Sub