Creating Recordset with SQL statement - sql

I am trying to create a recordset in Access VBA that will show me all records in a table related to the current record of a form. My current code looks like this:
Private Sub Form_Load()
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("Select [ID], [Ln] From [Order Detail] Where ((([Order Detail].[ID]) = [Forms]![Order Data Entry Header]![ID]))")
rst.MoveLast
Forms![Order Data Entry Header].LineNum = rst![Ln]
End Sub
I am doing this so that when adding new records they can be numbered sequentially after the highest number. When I run the form it get "Run-time Error: '3061' Too few parameters. Expected 1." on the Set rst line.
Any help would be appreciated.

The issue is the fact that the string you see there is exactly what is getting passed to the driver.
You need to "build up" the string, like so:
Set rst = CurrentDb.OpenRecordset("Select [ID], [Ln] From [Order Detail] Where ((([Order Detail].[ID]) = " & [Forms]![Order Data Entry Header]![ID] & "))")
Watch to make sure that [Forms]![Order Data Entry Header]![ID] is safe content, since you are building up an SQL statement.

Related

Return Query Value Using VBA function in Access

I'm currently working on a project and I've been having trouble trying to get a function that is able to return the value of a query, which I do need in order to display it on a textbox.
The current code is like this:
Public Function rubrieknaamSQL() As String
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT T_Train.trainPlate, T_Category.categoryName FROM T_Category INNER JOIN T_Train ON T_Category.id = T_Train.category_id WHERE (((T_Train.trainPlate)=[Forms]![F_Comboio]![Combo_Search_Comboio]));"
Set rst = CurrentDb.OpenRecordset(strSQL)
rubrieknaamSQL = rst!categoryName
rst.Close
End Function
I should say that the code is copied from other publisher and I do not own its rights. However, it still won't work when I try to run it and the error displayed goes like this:
Run-Time Error 3061 : Too few parameters. Expected 1
and it happens in Set rst command.
For a SELECT query to set a recordset object, concatenate variable:
" ... WHERE T_Train.trainPlate=" & [Forms]![F_Comboio]![Combo_Search_Comboio]
If trainPlate is a text field, need apostrophe delimiters (date/time field needs # delimiter):
" ... WHERE T_Train.trainPlate='" & [Forms]![F_Comboio]![Combo_Search_Comboio] & "'"
For more info about parameters in Access SQL constructed in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
There are ways to pull this single value without VBA.
make combobox RowSource an SQL that joins tables and textbox simply references combobox column by its index - index is 0 based so if categoryName field is in third column, its index is 2: =[Combo_Search_Comboio].Column(2)
include T_Category in form RecordSource and bind textbox to categoryName - set as Locked Yes and TabStop No
build a query object that joins tables without filter criteria and use DLookup() expression in textbox
=DLookup("categoryName", "queryname", "trainPlate='" & [Combo_Search_Comboio] & "'")

In access VBA, Is there a way to look-up a record in a table using a combo-box criteria and adding that record to a different table?

I am trying to use unbound comboBoxes and textBoxes where a user a updates the controls and clicks on a button and a new record is created in another tblEntry using some data of the same record from tblItems.
Problem: My code only works on the first record. It creates the new record in the tblEntry using data of the first record in tblItems. Can someone have a look please?
Private Sub addItem_Click()
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Set rs1 = CurrentDb.OpenRecordset("SELECT * FROM tblItems")
Set rs2 = CurrentDb.OpenRecordset("SELECT * FROM tblEntry")
If Not IsNull(Me.combo1) Then
rs2.AddNew
rs2.Fields("Description").Value = rs1.Fields("Description").Value
rs2.Fields("ItemNo").Value = rs1.Fields("ItemNo").Value
rs2.Fields("ItemName").Value = Me.txtItemName.Value
rs2.Fields("entryDate").Value = Me.txtentryDate.Value
rs2.Update
Form.frmItemEntryDatasheet.Requery
End If
rs1.Close
Set rs1 = Nothing
rs2.Close
Set rs2 = Nothing
End Sub
As #June7 says, there probably is no reason to do this. However, what you need to do is to open rs1 up filtered to just show data relating to that selected in combo1. Assuming that the first column in combo1 is the Primary Key from tblItem and called "ItemID":
Set rs1 = CurrentDb.OpenRecordset("SELECT ItemDescription, ItemNo FROM tblItems WHERE ItemID ='" & ItemID.Value & "'")
I have also renamed your field "Description" to "ItemDescription" as it is probably a reserved word within Access and may case problems. I have also just selected the 2 fields that you are going to use - there is no point getting all of the fields. You should be opening both recordsets within the If/End If statement.
Also, when you are opening rs2, you are effectively selecting the whole table. Far better is to use:
Set rs2 = CurrentDb.OpenRecordset("SELECT * FROM tblEntry WHERE 1 = 2")
This opens up a recordset based on tblEntry, but with no records selected, and so therefore has less overhead.
Regards,

simple use recordset to find text box value on report

I'm trying to learn how to use recordsets in VBA and starting here. I want to lookup the value from the ProductVars table and populate to a text box on a report for each record [ProductID].
The value I want is where Field [Name]="Hinging" and I need it to send the value from the Field [Value] to the txtHinge text box on the report.
Here is my current code.
Private Sub Report_Load()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
'Open a table-type Recordset
Set rs = db.OpenRecordset("ProductVars")
'Find the value of Hinging from the Name field Name and populate to txtHinge
for the ProductID
Do Until rs.EOF
Me.txtHinge = rs!Name.Hinging.Value
rs.MoveNext
Loop
End Sub
Any help would be greatly appreciated.
In textbox ControlSource:
=DLookup("[Value]", "PRODUCTVARS", "[Name]='Hinging' AND ProductID=" & [ProductID])
Or if multiple dynamic parameters must be considered:
=DLookup("[Value]", "PRODUCTVARS", "[Name]='" & [Name] & "' AND ProductID=" & [ProductID])
If the latter is the case, possibly could just include the PRODUCTVARS table in the report RecordSource with a compound join.

Why is the value extracted from database not showing what is intended?

I have the following SQL Statement:
SELECT StockChild.ProductId, Sum(StockChild.Qty) AS SumOfQty,
PRODUCTDETAILS.Title, Sum(SALESORDERchild.Stockout) AS SumOfStockout
FROM (PRODUCTDETAILS
INNER JOIN SALESORDERchild
ON PRODUCTDETAILS.productID = SALESORDERchild.ProductId)
INNER JOIN StockChild
ON PRODUCTDETAILS.productID = StockChild.ProductID
WHERE (((StockChild.ProductID)=[Forms]![StockChild]![ProductId])
AND ((SALESORDERchild.ProductID)=[Forms]![StockChild]![ProductId]))
GROUP BY StockChild.ProductId, PRODUCTDETAILS.Title;
I'm trying to get the summation of values from 2 different tables using the above SQL Statement in access:
1) Sum of StockChild quantity based on productID
2) Sum of Salesorderchild Stockout based on productID
If i query it separately, i managed to get the values that i needed but i'm unable to put it into a single form.
but when i query it together as above, the values jump all over the place and i can't seem to understand why.
And if i add another record in the salesorderchild, of the already existing isbn, all the values will jump as well.
is there something that i am doing wrongly? or how should i go about to tackle this matter.
I added some explanations in the image attached.
Update:
I was trying another method whereby i just did a normal query for the initial stock to be displayed(which worked fine getting the numbers i need)
and over in the Total stockout i was trying out a
=DSum("[stockout]","[SALESORDERchild]","[ProductId]=" & [Forms]!
[StockChild]![ProductId])
but it was returning me a #Name? did i use this correctly?, should i do a vba code instead or is there a way to do it this way?
i tried the following vba code function as an alternative to select out the value but it was telling me the user-defined type not defined. am i missing out something? - (fixed this part by defining the reference of active x data object)
Private Sub Form_Current()
Dim intI As Integer
Dim fld As Field
Dim rst As ADODB.Recordset
Dim pid As String
pid = ProductID.Value
Set rst = New ADODB.Recordset
rst.Open "SELECT Sum(SALESORDERchild.Stockout) AS SumOfStockout FROM
SALESORDERchild WHERE SALESORDERchild.ProductID ='" & pid & "';",
CurrentProject.Connection, adOpenKeyset, adLockOptimistic
tb_stockout.Value = rst.Fields("SumOfStockout")
End Sub
Done Thanks everyone :)

How do take the value from a combobox and use it to run an SQL query

I am trying to take the value from a combo box (in this case 'cboFullName' located on form 'frmMasterNotebook') and cross reference it to table 'tblSearchEngine01' so that an update gets made to column 'query05contactselect' for all records where in column 'contact' the value matches to that selected by the combobox ('cboFullName'). Below is my code but I am getting a syntax error message.
Private Sub cboFullName_AfterUpdate()
st_sql = "UPDATE tblSearchEngine01, SET tblSearchEngine01.Query05ContactSelect = '1' WHERE (((tblSearchEngine01.[contact])=([forms]![frmmasternotebook]![cbofullname]))))"
Application.DoCmd.RunSQL (st_sql)
Your code builds an UPDATE statement which includes a comma after the table name ...
UPDATE tblSearchEngine01, SET
^
Remove that comma and see whether Access complains about anything else.
However I suggest you start by creating and testing a new query in Access' query designer. Paste this statement into SQL View of your new query ...
UPDATE tblSearchEngine01
SET Query05ContactSelect = '1'
WHERE [contact] = [forms]![frmmasternotebook]![cbofullname];
After you revise and test the statement so that Access executes it without complaint, then you can revise your VBA code to produce the exact same statement text which works in the query designer.
Using DAO this is another way to resolve my issue:
Private Sub cboFullName_AfterUpdate()
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("tblSearchEngine06", dbOpenTable)
rst.AddNew
rst!Contact = Me.cboFullName.Text
rst!ContactID = Me.cboFullName
rst.Update
rst.Close
Set rst = Nothing