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.
Related
My Database has 3 tables Inventory (Item Name, Barcode, Unit Type), In (Lot #, Barcode, Location, Expiration Date, Received Date), Out (Barcode, Team, Person Removing, Out Date). I have an unbound form for when I add a new Item to the main inventory. I would also like it to add the information to the In Table from the same unbound fields in the form. The unbound Field names are Item, Unit, Barcode, Lot, Expiration. I have tried using the “INSERT INTO” but cannot get it to work, I have never used it before.
Use this code: (make sure you keep In with [] since In is a reserved word)
strSQL = "INSETR INTO [In] (Item, Unit, Barcode, Lot, Expiration) "
strSQL = strSQL & "(" & Me.Item & "," & Me.Unit & "," & Me.Barcode & "," & Me.Lot & "," & Me.Expiration & ")"
DoCmd.RunSQL strSQL
Found It!!! Typed it all in by hand and it works not sure why but it does.
https://www.youtube.com/watch?v=Cgtk7LrtmJk
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.
My database has three tables, Holder, Product (which is an account) and Transaction. I have set up a form from the Holder table that has a subform from the Product table and the Product subform has the Transaction table as a subform. On the Holder portion of the form, I have put an Outstanding unbound text field that should display the total amount and tax fields of transactions from the transaction table that have not been paid (indicated by a checkbox on the Transaction table). I have set the control source of the unbound text box to =calcOutstanding() and written the following function for the form.
Public Function calcOutstanding()
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
& "FROM tblTransaction" _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
& "WHERE tblTransaction.TxPaid = False" _
& "AND tlbHolder.HolderID = Me.HolderID;"
DoCmd.RunSQL strSQL
calcOutstanding = Outstanding
End Function
The field now just shows #Error. What am I doing wrong?
There's a bunch wrong with your approach:
DoCmd.RunSQL is just for action queries (INSERT, UPDATE, DELETE).
You cannot return a value from DoCmd.RunSQL like you are attempting to and push it into a variable.
Your concatenation for the where clause is incorrect.
As HansUp mentioned, Access is very picky about parentheses in JOINs in its SQL.
Assuming the SQL is correct, this code lives on the parent form, and you dno't get multiple rows back in your query, maybe something like this would work:
Public Function calcOutstanding() As Currency
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding " _
& "FROM (tblTransaction " _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID) " _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID " _
& "WHERE tblTransaction.TxPaid = False " _
& "AND tlbHolder.HolderID = " & Me.HolderID
Set rst = db.OpenRecordset(strSQL, dbForwardOnly)
calcOutstanding = rst![Outstanding]
Set rst = Nothing
set db = Nothing
End Function
Notice the concatenation in the WHERE clause to get the value from the form's data source (otherwise the SQL couldn't reconcile Me.HolderID within the scope of the SQL itself). Also, we push the returning dataset into a recordset and read from that. Something along these lines should work, I think. (Not in front of Access now, so sorry if any non-compiling statements.)
EDIT: Added the function return type as integer for specificity's sake.
EDIT 2: Added the function return type as currencyfor specificity's sake. Doh.
Right off the bat, I see a problem in the code you posted:
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
& "FROM tblTransaction" _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
& "WHERE tblTransaction.TxPaid = False" _
& "AND tlbHolder.HolderID = Me.HolderID;"
There should be a space either at the end of each line Outstanding " _ or at the beginning of each line like " FROM tblTransaction otherwise your string will read OutstandingFROM tblTransaction when parsed, which will give you an error.
I doubt you need an external function to do this. MS Access allows you to reference fields from subform simply by Me.Subform!FieldName.Value
This means, you could simply access the subform fields that are related to your current record. Even perform IIF(condition, truevalue, falsevalue) on that field
read more about accessing forms and subforms here: http://access.mvps.org/access/forms/frm0031.htm
EDIT:
in your third subform (tbl_transaction), create a new unbound TextBox called (txt_outstanding) and assign this expression
=IIF([txPaid]=false, sum(txAMount +TxTax),0)
now you can access this field in your parent form something similar to this:
me.txt_someTextbox.value = nz(me.tbltransactionsubform!txt_outstanding.value,"")
I have table x that contains id and name fields.
I want to display the id when I select the name in the list.
I wrote this but it doesn't work.
The error msg is: either BOF or EOF or current record has been deleted.
Requested operation requires a current record.
I think simply the default record is record 1, so what's wrong ?!
Dim con As Connection
Dim rs As New Recordset
Set con = CurrentProject.Connection
rs.Open "select id from tbl where namen = '" & list1.ListIndex & "'", con, adOpenDynamic, adLockOptimistic
ttt.SetFocus
ttt.Text = rs!id
thank you so much pteranodon for your help
I changed the code to be like this
Private Sub list1_Click()
Dim strSQL As String
strSQL = "select id from tbl where namen = '" & list1.Value & "'"
ttt.SetFocus
ttt = DLookup("id", "tbl", "namen='" & list1.Value & "'")
rs.Open strSQL, con, adOpenDynamic, adLockOptimistic
End Sub
but I got this msg
operation is not allowed when the object is open ?
I didn't add the items to the list1 by using vba code I just followed the window that show up after adding the list1 to the form cus I also have problem with code
if you please can you add the complete code 1 and 2
You want the value of the listbox, not ListIndex. ListIndex contains a number, the zero-based index of the current selection in the listbox. You are passing in something like select id from tbl where namen = '13' Since no records match, you get that error message.
I really reccommend using a string to hold any constructed SQL so that you can debug it easily. If you had
Dim strSQL As String
strSQL = "select id from tbl where namen = '" & list1.Value & "'"
Debug.Print strSQL
rs.Open strSQL, con, adOpenDynamic, adLockOptimistic
it would be easier to read and much easier to debug. Also, you'll want to check for rs.BOF and rs.EOF right after opening a recordset:
If Not (rs.BOF Or rs.EOF) Then
'Do stuff
Else
'No records in recordset
End
Unlike VB textboxes, you can't use .Text in VBA textboxes unless the textbox has the focus. Use ttt.Value (or just ttt instead).
And if you are only looking up a single value like this you can replace all of your code like this:
Private Sub list1_Click()
ttt = DLookup("id", "tbl", "namen='" & list1.Value & "'")
End Sub
Using DLookup instead of manually opening a recordsest yourself. I would also go back through the listbox wizard. If you put the id in the first column and the name in the second, then hide the first column (the wizard will help you do this), the list will show the name but store the id. Then you don't even need the extra textbox. The id is stored in List1.Value and the name is available as List1.Column(1).
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.