Getting current selected record value in access subform - ms-access

I have 2 subforms in access 2010 database; Based on selection of subform1 field value , the vba program will run the subform2 output which common text fields in subform 1 and 2 as "supplier_name".
So, I tried the "on double click" event on subform1 to write the currentRecord method see below,
Private Sub Supplier_name_DblClick(Cancel As Integer)
strSQL = "Select * from [Query1] where"
strSQL = strSQL & "[Supplier_name] ="'" & "Me!current record![Supplier_name]" &"'"
Form![Mainform]![Subform2].Form.RecordSource = strSQL
End Sub
I am getting Run-time error 3075 at the 2nd line; Syntax error (missing operator) in query expression '[Supplier_name] =Me!current record![Supplier_name]'
Please help

Thanks it worked for me but without the currentrecord property
strSQL = strSQL & "[Supplier_name] ='" & Me![Supplier_name] & "'"

You are missing a space after the where in the second row of your code:
strSQL = "Select * from [Query1] where "
and there is also a problem with your " and ' chars in the third line:
strSQL = strSQL & "[Supplier_name] ='" & Me!current record![Supplier_name] & "'"

Related

how can I put a variable in an sql command string in vba access?

letter=65
is a variable representing a letter (A) in the alphabet.
I want to insert letter into part of an sql command string:
sqlUrlCount = "SELECT tblMain.Name FROM tblMain WHERE (((tblMain.Name) Like '" & Chr(letter) & "*'))"
but I get an error: "Run-time error '3075': Syntax error in string in query expression '(((tblMain.Name) Like".
this is probably because of the quotes and double quotes I used. but how else can I do this?
Your syntax is correct so try to copy-n-paste the resulting string:
SELECT tblMain.Name FROM tblMain WHERE (((tblMain.Name) Like 'A*'))
into a new query.
If it fails, adjust the SQL and then your code.
If it runs, then rewrite your code line (no copy-n-paste), then delete the old code line.
When I tried to create a field called 'Name' in Access it complained that it was a reserved word - could be part of the problem.
The code below returned an SQL string which worked when I pasted it into the query window (note - have updated 'Name' to 'sName' and the field type is Text).
Also note - Access loves putting brackets around everything and most of the time they're not required.
Sub test()
Dim letter As Long
Dim sqlUrlCount As String
letter = 65
sqlUrlCount = "SELECT sName FROM tblMain WHERE sName Like '" & Chr(letter) & "*'"
End Sub
Edit:
To use a SELECT query:
Sub Test()
Dim sqlUrlCount As String
Dim letter As Long
Dim rst As DAO.Recordset
letter = 65
sqlUrlCount = "SELECT tblNewMain.WebAddressCompareString, " & _
"Count(*) AS [How Many?] FROM tblNewMain " & _
"WHERE (((tblNewMain.WebAddressCompareString) Like '" & Chr(letter) & "*')) " & _
"GROUP BY tblNewMain.WebAddressCompareString HAVING (((Count(*))>1))"
Set rst = CurrentDb.OpenRecordset(sqlUrlCount)
With rst
If Not .BOF And Not .EOF Then
.MoveFirst
Do
Debug.Print .Fields("WebAddressCompareString") & " : " & .Fields(1)
.MoveNext
Loop Until .EOF
End If
.Close
End With
Set rst = Nothing
End Sub
If it's a DDL or DML type query - i.e. UPDATE, CREATE TABLE, SELECT INTO, etc then you can use DoCmd.RunSQL

display a table field in a list using condition

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).

Assign control source dynamically from a different recordset

I have the following VBA code in my access.
Dim subform As Object
Dim formFilter As String
formFilter = "..." 'a SQL statement
Set subform = Me!my_subform.Form
subform.RecordSource = formFilter
subform.field1.ControlSource = "f1"
subform.field2.ControlSource = "f2"
subform.field3.ControlSource = "f3"
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT TOP 1 f4 FROM my_table " _
& "WHERE tableF1= '" & [f1] & "' AND tableF2 = '" & [f2] & "' " _
& "ORDER BY tableF5 DESC")
subform.field4.ControlSource = rs(0)
I have first bound my first 3 fields in subform to the fields of my record source. Then I need to bind the 4th field to a different recordset. This recordset has to refer to the first 2 fields of my subform.
However, I got a run-time error 2465. Access is not able to refer to the field [f1] and [f2] of my OpenRecordSet statement.
How should I fix this?
I use this form in a datasheet view. So I need to refer to not a single value of field1 and field2, but the entire columns of records have to be linked.
Thanks a lot.
(from an earlier edit to the question, since rolled back:)
Apparently the solution in this case was to use the following code in the On Load event handler for the subform instead of the main form
Dim db As Database
Dim rs As Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT TOP 1 f4 FROM my_table " _
& "WHERE tableF1= '" & [f1] & "' AND tableF2 = '" & [f2] & "' " _
& "ORDER BY tableF5 DESC")
subform.field4.ControlSource = rs(0)
because the [f1] and [f2] controls were on the subform and therefore not visible from the Class Module code for the main form.

Error 3061 Too few parameters 2 expected

I have been facing the error 3061 with error message "Too few Parameters: Expected 2". I have done all of the following to resolve the issue but still couldn't it.
I ran the query in SQL mode and it gives me result
I checked all the field names
I checked all the "&" s are placed. I find them correct.
Here is my code:
Private Sub cmbYear_Change()
Dim db As Database
Dim rs As DAO.Recordset
Dim Query As String
Query = " SELECT Yrs_Teaching, Highest_Edu, AD_Descr FROM ClassSurvey" & _
" WHERE ClassSurvey.Program/School_ID = " & Me.cmbProgId.Value & _
" AND ClassSurvey.ClassID = " & Me.cmbClassId.Value & _
" AND ClassSurvey.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND ClassSurvey.SYear = " & Me.cmbYear.Value
Set db = CurrentDb
Set rs = db.OpenRecordset(Query)
If rs.RecordCount > 0 Then
Me.TB1 = rs!Yrs_Teaching
Me.TB2 = rs!Highest_Edu
Me.TB3 = rs!AD_Descr
Else
Me.TB1 = "N/A"
End If
Set rs = Nothing
Set db = Nothing
End Sub
It appears your table includes a field named Program/School_ID. Bracket that field name in the SELECT statement so the db engine can properly recognize it as one field name.
That change might be all you need. But if you have another problem, give yourself an opportunity to examine the completed SELECT statement you're giving to the db engine. It might not be what you expect.
Dim db As Database
Dim rs As DAO.Recordset
Dim strQuery As String
strQuery = "SELECT cs.Yrs_Teaching, cs.Highest_Edu, cs.AD_Descr FROM ClassSurvey AS cs" & _
" WHERE cs.[Program/School_ID] = " & Me.cmbProgId.Value & _
" AND cs.ClassID = " & Me.cmbClassId.Value & _
" AND cs.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND cs.SYear = " & Me.cmbYear.Value
Debug.Print strQuery
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery)
If you get an error, you can go to the Immediate window (Ctrl+g), copy the statement text from there, open a new query in the query designer, switch to SQL View, paste in the statement text and try running it there. This tip is especially useful when the db engine complains about a missing parameter because when you try to run the query from the designer, Access will show you an input box asking you to supply a value and that box also contains the name of whatever Access thinks is the parameter.
I came across this when I was looking for a solution to the same problem. Turns out one of the values from a control on the form was not passing the value to the statement, sending it to the debug window (Debug.print) helped me spot the problem after a long time because I was using a global variable which the sql query was parsing. So load your controls' values into variables first!
This error may be because the column names in the query have special characters. Try surrounding the column names with square brackets in the SQL query. Column name with special symbols should be within square brackets and variables should be inside single quotes.
I had this issue too, I realized it was because I did not put quotes around my variables.
This was fixed by adding '& Chr(34)' around my variables
My fixed code looks like:
TextProducer = [Forms]![MyFormName]![TextInputBoxName]
strQuery = "SELECT FILEMASK" & _
" FROM TABLE_NAME" & _
" WHERE Producer = " & Chr(34) & TextProducer & Chr(34)

how to update a mainform into a subform

After I edit information and change the information and click update, it gives me a error. I tried the parenthesis brackets no luck.
Too few parameters Expected 1. Run time error '3061'
Private Sub cmdUpdate_Click()
Dim strSql As String
strSql = "UPDATE PlantTransaction " & _
"SET TransactionID=" & Me.txtTranID & _
",[Plant Number]='" & Me.txtPlantNo & "'" & _
",TransactionDate=#" & Me.txtTransDate & "#" & _
",Opening_Hours='" & Me.txtOpeningHRS & "'" & _
",Closing_Hours='" & Me.CloseHrs & "'" & _
",Fuel='" & Me.txtFuel & "'" & _
",[Fuel Cons Fuel/Hours]='" & Me.txtFuelConsFuelHr & "'" & _
",[Hour Meter Replaced]='" & Me.txtHrMtrRep & "'" & _
",Comments='" & Me.txtComments & "'" & _
",[Take on Hour]='" & Me.txtTOH & "'" & _
" WHERE TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
Debug.Print strSql ' <- prints to Immediate window
CurrentDb.Execute strSql, dbFailOnError
cmdClear_Click
Me.PlantTransactionQuery.Form.Requery
End Sub
You were smart to include this line in your code:
Debug.Print strSql ' <- prints to Immediate window
Now when you get the missing parameter message, go to the Immediate window (you can use Ctrl+g to go there) and copy the SQL statement.
Then create a new Access query in the query designer, switch to SQL View, and paste in the text you copied. When you attempt to run that query, Access will present a parameter input box which includes the name of whatever it thinks is the parameter.
Compare that parameter name with the field names in your data source. Often this situation occurs because the query includes a misspelled field name. Another possibility with an UPDATE is that one of the values you're trying to update is unquoted text. Regardless of the cause, the parameter name from that input box should help you track it down. Show us the actual text from that UPDATE statement if you need further help.
Any time that you "glue together" a long SQL statement with lots of user input you face the challenges of
correctly delimiting strings and dates,
escaping delimiters within such fields (usually quotes inside a text field), and
getting all of the required commas in the right places
You can avoid those annoyances by using a Recordset to perform the update:
Dim rst As DAO.RecordSet
Set rst = CurrentDb.OpenRecordset("PlantTransaction", dbOpenDynaset)
rst.FindFirst "TransactionID=" & Me.PlantTransactionQuery.Form.Recordset.Fields("Tr ansactionID")
If Not rst.NoMatch Then
rst.Edit
rst!TransactionID = Me.txtTranID
rst![Plant Number] = Me.txtPlantNo
rst!TransactionDate = Me.txtTransDate
rst!Opening_Hours = Me.txtOpeningHRS
rst!Closing_Hours = Me.CloseHrs
rst!Fuel = Me.txtFuel
rst![Fuel Cons Fuel/Hours] = Me.txtFuelConsFuelHr
rst![Hour Meter Replaced] = Me.txtHrMtrRep
rst!Comments = Me.txtComments
rst![Take on Hour] = Me.txtTOH
rst.Update
End If
rst.Close
Set rst = Nothing