display a table field in a list using condition - ms-access

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

Related

Create a query from a button on a form

I have a form with a button on it.
I want the button to create a query from a table (which the form populates)
I made the button, went to the code builder
Private sub button123_on click()
End sub
I've looked up queries in DOA but i cant figure it out, or even know if that is what im supposed to be using. I just need to know what comes after private sub
If statements?
Dim stuff?
doCmd?
🤷🏾‍♂️
Im just looking for the basic layout
Do i build the query elsewhere and then put a command to run it for the button? It has to be in VBA because i need to select the TOP variable# of records. The TOP changes so i cant do it in sql.
After some research this is my code
Private Sub Command487_Click()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strSQL As String
Set db = CurrentDb
Dim varX As Variant
Set qdef = db.CreateQueryDef("MyQuery")
Application.RefreshDatabaseWindow
varX = DLookup("[Quantity1]", "tblFilledRequests", "[OrderID] = [Forms]![frmFilledRequests]![OrderID]")
strSQL = "SELECT TOP varX tblFilledRequests.OrderID, tblFilledRequests.RequestFillDate, tblFilledRequests.Issuer, tblFilledRequests.Unit, tblFilledRequests.ContactNumber, tblFilledRequests.CommonName1, tblFilledRequests.Quantity1, tblFilledRequests.CommonName2, tblFilledRequests.Quantity2, tblWeapons.IssueCount, tblWeapons.StockNumber, tblWeapons.SerialNumber, tblWeapons.Status " _
& "FROM tblWeapons INNER JOIN tblFilledRequests ON tblWeapons.WeaponID = tblFilledRequests.CommonName1 " _
& "WHERE (((tblFilledRequests.OrderID)=Forms!frmFilledRequests!OrderID) And ((tblWeapons.Status)=""AVAILABLE"")) " _
& "ORDER BY tblWeapons.IssueCount, tblWeapons.StockNumber;"
qdf.SQL = strSQL
DoCmd.OpenQuery "MyQuery"
qdf.Close
Set qdef = Nothing
Set db = Nothing
End Sub
I get a blank query and i get an error message qdf.SQL object variable or with block variable not set
I'm going to assume that you want to execute that query and display the results in an element on your form, for example, a listbox.
I've made a form with:
A textbox named txtTopX that will allow the user to input the amount of records they want to retrieve.
A button that will execute the query and show the results (btnQuery)
A listbox that will display the results. I've named it lstResults and set the Column Count property to the amount of columns my query will return. (in this example, 3)
The code on the form is this:
Private Sub btnQuery_Click()
Dim limit As Integer
'Determine the TOP X limit
If IsNumeric(Me.txtTopX.Value) Then
limit = Me.txtTopX.Value
Else
limit = 5 'Some default value incase the input from the textbox is not a number
End If
'Set the rowsource of the listbox to the query's results
lstResults.RowSource = "SELECT TOP " & limit & " col1, col2, col3 FROM Table1 ORDER BY ID DESC"
End Sub
The table in this example is Table1 and has 4 columns: ID, col1, col2 and col3. In my query I'm only showing 3 columns and using the ID column to sort my records on. (as you're planning to use TOP X, I think you want to show the TOP X most recent records)
thank you for the advice, Grimlor.
no, i am not trying to display the results of the query on the current form. I actually need to display them in an array on another form, but that is a little down the road.
i need to write the query in VBA
for my TOP I used the DLookup function. and defined varX as a variable
varX = DLookup("[Quantity1]", "tblFilledRequests", "[OrderID] = [Forms]!
[frmFilledRequests]![OrderID]")
i will take what i can from your answer
Private Sub Command490_Click()
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim strSQL As String
Dim limit As Integer
limit = Me.Quantity1.Value
On Error Resume Next
DoCmd.DeleteObject acQuery, "testQry"
On Error GoTo 0
strSQL = "SELECT TOP " & limit & " tblFilledRequests.OrderID,
tblFilledRequests.RequestFillDate, tblFilledRequests.Issuer,
tblFilledRequests.Unit, tblFilledRequests.ContactNumber,
tblFilledRequests.CommonName1, tblFilledRequests.Quantity1,
tblFilledRequests.CommonName2, tblFilledRequests.Quantity2, tblWeapons.IssueCount,
tblWeapons.StockNumber, tblWeapons.SerialNumber, tblWeapons.Status " & vbCrLf & _
"FROM tblWeapons INNER JOIN tblFilledRequests ON tblWeapons.WeaponID =
tblFilledRequests.CommonName1 " & vbCrLf & _
"WHERE (((tblFilledRequests.OrderID)=[Forms]![frmFilledRequests]![OrderID]) AND
((tblWeapons.Status)=""AVAILABLE"")) " & vbCrLf & _
"ORDER BY tblWeapons.IssueCount, tblWeapons.StockNumber;"
Set qdf = db.CreateQueryDef("testQry", strSQL)
DoCmd.OpenQuery ("testQry")
End Sub
It all works beautifully. Thank you

TempVars - Get ID for use in next form

In my database the user creates a new record via a form like so;
Upon pressing the save button, the record then gets inserted into ConTblConsumables, Here is the code sample behind the save button;
Private Sub btnSave_Click()
Dim strAddNewConsumable As String
Dim strCompany As String
Dim strConName As String
Dim strConID As String
Dim strCboConSupplier As String
Dim strConTargetLevel As String
Dim strConCost As String
strCompany = Me.ConCompany
strConName = Me.txtConName
strConID = Me.txtConID
strCboConSupplier = Me.CboConSupplier
strConTargetLevel = Me.txtConTargetLevel
strConCost = Me.txtConCost
strAddNewConsumable = "INSERT INTO ConTblConsumables(strConCost, ConName, ConExtraID, Supplier, ConTargetLevel, Cost)" _
& "VALUES('" & strCompany & "', '" & strConName & "', '" & strConID & "', '" & strCboConSupplier & "', '" & strConTargetLevel & "', '" & strConCost & "')"
CurrentDb.Execute (strAddNewConsumable)
MsgBox "Record Inserted", vbExclamation
End Sub
Once the record has been inserted I then wish to pop-up another form where the user can then assign a parent machine to this part. The reason I wish to do it this way is that several machines can use the same part (Many-to-Many). Which when the machine is selected will then update this table;
The consumable column is a ComboBox with a relationship to the ConTblConsumables table and thus why I require to have the ID from previous to be retained in a TempVar.
I believe that if I was to use TempVars towards the end of the code on the save button, that when the record is inserted into the table ConTblConsumables, that the TempVars records the ID of the row that the record has been inserted into, thus being about to attain the ID for use in the next form.
My question is how do I write this in code? Or even if this is possible?
Thank you
As I understand, in table ConTblConsumables you have a key column ID with Autonumber data type and you need to know ID of inserted row. If so, you'd better to use recordset instead of INSERT statement. Something like this:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("select * from ConTblConsumables")
With rst
.AddNew
'here ID already known and you can store it in your variable
TempVars!MyID = !ID.Value
!strConCost = Me.ConCompany
!ConName = Me.txtConName
....
.Update
End With
rst.Close
Set rst = Nothing

Microsoft Access 2010 interdependencies in Forms (fill out one cell, automatically fill another)

In excel, I know this is the VLOOKUP function, however, being a beginner at Access, I have no clue how to do this.
I have halls (from A to H), who all have their own teamleader (eg A-->Ben, B-->Michael, C-->Dave, etc). I would like to select just the hall, and the teamleader will automatically show up in the next field on the form. At the end, all will be registered in a table.
I have currently build this equation to fill out a specific value in a cell (dependent on the value of another cell), but it is giving an error message. What am I doing wrong?
Option Compare Database
Dim db As DAO.Database
Dim rst As DAO.Recordset
Private Sub Hal_AfterUpdate()
Set db = CurrentDb
'SELECT Voormannen.Voorman, Voormannen.Hal
'FROM Voormannen
'WHERE (((Voormannen.Hal)=[Formulieren]![DSM formulier]![Hal]));
strSQL = "SELECT Voormannen.Voorman, Voormannen.Hal FROM Voormannen WHERE [Voormannen]![Hal]=[Forms]![DSM formulier]![Hal]"
Set rst = db.OpenRecordset(strSQL)
rst.MoveFirst
Me.Tekst304 = rst![Voorman]
rst.Close
Set rst = Nothing
Me.Refresh
End Sub
Assuming your SQL string returns a correct dataset, try replacing this:
Me.Tekst304 = rst![Voorman]
with this:
Me.Tekst304.Text = rst("Voorman")
If your SQL string does not return a correct dataset, try changing it to this:
strSQL = "SELECT Voorman, Hal FROM Voormannen " & _
"WHERE Hal = '" & Forms![DSM formulier]!Hal.Text & "'"
You need to surround your control reference with ampersands (&) otherwise VBA doesn't know you're referencing a control.

Getting current selected record value in access subform

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] & "'"

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.