Set form's combobox default value from first table value, Access - ms-access

I lookud up information about this topic, but without any effect.
I have a Access' table called TbKlient, which contains columns ID (primary key, autonumbered) and Name (Name of the Company) and Form FormVT1 with combobox cbName. My aim is simple but I can't achieve this. So I want, when I open this form, auto populate default value of cbName combobox with first row of TbKlient's Name column.
Appreciate all sugestions. Thank you!

Try to assign onOpen event form form FromVT1
Private Sub Form_Open(Cancel As Integer)
dim rst as recordset
set rst=currentdb().openrecordset("SELECT [Name] FROM [TbKlient] ORDER BY [ID]") ' author, please check if you really want record with the lowest ID that is called by you "first record"
if not rst.eof then
Me.cbName.DefaultValue = rst![Name]
end if
rst.close
set rst=nothing
end sub

Related

Setting the value of an Access combobox with VBA comparison

I'm trying to figure out where I went wrong with this.
I have two tables Request and Parent. Request can only have one related Parent record, but Parent can have many related Request records. So I have the Request table containing the foreign key to Parent.
I have an unbound combobox that pulls it's data from the Parent table using a query (contains company name and ID bound to column 0 and 1, with column 1 being hidden so the user doesn't see the numeric ID). It's unbound because the form's recordset has a lot of complex joins, making anything on that form unable to be updated. So I created an "On Change" event on the combo box to fill in the foreign key using a querydef SQL update query:
Private Sub Combo217_Change()
Dim ComboID As String
Dim ReqID As Long
Dim dbs As DAO.Database
Dim qdfUpdateParentExisting As DAO.QueryDef
ReqID = Me.RequestID.Value
ComboID = Me.Combo217.Column(1)
Set dbs = CurrentDb
Set qdfUpdateParentExisting = dbs.QueryDefs("UpdateReqExistingParent")
qdfUpdateParentExisting.Parameters("VBParent").Value = ComboID
qdfUpdateParentExisting.Parameters("VBReqID").Value = ReqID
qdfUpdateParentExisting.Execute
qdfUpdateParentExisting.Close
DoCmd.Save acForm, "DT2"
Me.Requery
End Sub
This works just fine, but once you exit the form and re-enter it, the value in the combo box is blank and I would like this to contain the same value that was selected.
I've been trying to do an "On load event" with the following code but it's not working
Dim ParID
ParID = Me.ParentID.Value
Me.Combo217.Column(1).Value = ParID
Any input on getting this to work would be fantastic!
Because it's tied to specific column you can loop thru to set the value based on the matching ID
EDIT - Add Row index to Column Value
Dim i as Integer
With Combo217
For i = 0 To .ListCount - 1
If .Column(1, i).Value = ParID Then
.Value = .ItemData(i)
Exit For
End If
Next
End With

Alert of duplicate name in Access 2003, despite a duplicate I want to decide if include it or not

I have a table with this fields:
ID(Autonumeric)
Name(Text)
And I have a form, this form has a TextBox for input the name.
Example of input
1.John
2.Katie
As soon I finish input the name in the TextBox, I want to show an alert that show if the record is duplicated.
Example:
If I input again:
3.Katie
The program needs to show me a message like this: "Duplicate name, do you want to save it or not?"
Use the text box's Before Update event to check whether its current value is already stored in your table.
If your text box is named txtName and YourTable is the table which contains the Name field, this should do what you want:
Private Sub txtName_BeforeUpdate(ByRef Cancel As Integer)
Dim qdf As DAO.QueryDef
Dim strSelect As String
strSelect = "SELECT Count(*) FROM YourTable WHERE [Name]=[which_name];"
Set qdf = CurrentDb.CreateQueryDef(vbNullString, strSelect)
qdf.Parameters("which_name").Value = Me!txtName.Value
If qdf.OpenRecordset()(0) > 0 Then
If MsgBox("Duplicate name, do you want to save it or not?", vbYesNo) = vbNo Then
Cancel = True
End If
End If
End Sub
When a match is found, and the user clicks "No" at the MsgBox, the next line .. Cancel = True ... aborts the text box value update, leaving the cursor in the text box. The user must change the text box value or agree to store the duplicate value before they can proceed past that text box.

Combobox with LimitToList set to false with non-bound field

I have a products table and a tags table with a many-to-many relationship. I also have a pivot table that store the product id and the tag id.
I'd like to be able to show the tag text in the combo box but store the id. This on its own is simple as I can just adjust the column width of the id, however, I'm trying to set LimitToList to No so I can implement some VBA to filter the list when I type in the combo box, but this only appears to be possible if the first column is the bound column, which means the tag id appears in the combo box instead of the text.
How do I show the tag text in the combobox and allow 'LimitToList' to be false?
Leave LimitToList on Yes, and use the NotInList event of the combobox instead.
E.g.
Private Sub cboTag_NotInList(NewData As String, Response As Integer)
Dim RS As Recordset
If MsgBox("Do you want to add '" & NewData & "' as new Tag?", vbYesNo + vbQuestion) _
= vbYes Then
' Add the new tag
Set RS = CurrentDb.OpenRecordset("tbTags")
With RS
.AddNew
!Tag_Text = NewData
.Update
.Close
End With
Response = acDataErrAdded
Else
Response = acDataErrDisplay
' Or a user defined MsgBox and acDataErrContinue
End If
End Sub
(sigh) again I have misunderstood your question. :(
To filter the combobox as the user types a part of a Tag, you use the Change event. This works just fine with LimitToList = Yes.
Private Sub cboTag_Change()
Me.cboTag.RowSource = _
"SELECT Tag_ID, Tag_Text FROM tbTags WHERE Tag_Text LIKE '*" & Me.cboTag.Text & "*'"
' With the instant filtering, it is more convenient for the user
' to always see the filtered dropdown
Me.cboTag.Dropdown
End Sub
Of course at some point the user has to select a Tag from the list. Otherwise there would be no ID to store in the field.
Or if you want him to be able to add new tags, use the code from the other answer. Both events work together as written.
Search-as-you type technique described very good here, including automatic selection of items from opened dropdown combobox after typing few characters.

Combo box in form (Access 2010) - Retrieving values from 2 different fields

I need to create a Form on access 2010 that navigates among records from a table (t_main)
but the problem is that I need a combo to select among param1_old and new and also among param2_old and new.
This combo will have 2 values, the old and the new for each parameter. In the end, after I select which parameters I want to keep for this user, I will click in a button and save this information into a new table (t_saved).
t_main has the following structure:
user; date; name; param1_old; param1_new; param2_old; param2_new
and
t_saved has the following structure:
user; date; name; param1; param2
Any idea on how to do that? Should I work with recordsets? is there a way to avoid it and just force the combo to take values from 2 different fields into a value list?
Thanks a lot for any help!
edit:
I know it is rather complex to understand what I need, I will try to show in a screenshot:
the data in the table are as following:
user; date; name; param1_old; param1_new; param2_old; param2_new
1234568789;"21/07/2014";"John Smith";'Lemon street 125';'Avocado avenue 123'; '...'; '..'
You don't mention what is the primary key in each tables, so I will assume it's the user field and that each record in t_main and t_saved has a unique user.
If not, then substitute that with the actual primary key.
Note that date is a reserved keyword and you cannot name a field date, so I renamed it thedate instead.
I have created a small sample database that works as you describe (at least as I understand it).
I created these tables with some sample data:
I created a form bound to the t_main table:
Note that the dropdown boxes cbParam1 and cbParam2 are not bound to any field, they are left unbound.
The rowsource for the dropdown boxes is a bit of a hack, but it works well.
For instance, for cbParam1.RowSource:
SELECT param1_old
FROM t_main
WHERE user=Forms![FormMain]![User]
UNION ALL
SELECT param1_new
FROM t_main
WHERE user=Forms![FormMain]![User];
This query selects both the old and new fields from the t_main record that has the same user as the one currently displayed. In effect, it shows both old and new parameters for the current record in the combobox.
The code behind the FormMain is mostly used to manage the display.
Here we prevent the user from adding the data to t_saved if one f the dropdown boxes is empty, or if we've already added that record before.
Option Compare Database
Option Explicit
' We use this variable to keep track of whether the
' record was already found in the t_saved table
Private alreadysaved As Boolean
'-----------------------------------------------------------------------------
' Update the UI after we change our selection of parameter
'-----------------------------------------------------------------------------
Private Sub cbParam1_AfterUpdate()
UpdateUI
End Sub
Private Sub cbParam2_AfterUpdate()
UpdateUI
End Sub
'-----------------------------------------------------------------------------
' Enable/Disable the save button.
' The button is only enabled if the user selected both parameters
'-----------------------------------------------------------------------------
Private Sub UpdateUI()
btAddData.Enabled = Not (IsNull(cbParam1) Or IsNull(cbParam2)) _
And Not alreadysaved
End Sub
'-----------------------------------------------------------------------------
' Refresh teh data every time we change record
'-----------------------------------------------------------------------------
Private Sub Form_Current()
' Reset the values of the parameters comboboxes
cbParam1 = Null
cbParam2 = Null
cbParam1.Requery
cbParam2.Requery
' Check if there is already a record for the same user in the t_save table
alreadysaved = DCount("user", "t_saved", "user='" & user & "'") > 0
' Display a warning to tell the user the current record cannot be saved again
lblInfo.Visible = alreadysaved
UpdateUI
End Sub
The important bit of code is actually the one that adds the data to a new record int he t_saved table:
'-----------------------------------------------------------------------------
' The button was clicked.
' Save the current record data to the t_save table
'-----------------------------------------------------------------------------
Private Sub btAddData_Click()
' We create a new new record in t_save and copy our data
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb()
Set rs = db.OpenRecordset("t_saved", dbOpenDynaset, dbFailOnError)
With rs
.AddNew
!user = user
!thedate = thedate
!name = name
!param1 = cbParam1
!param2 = cbParam2
.Update
.Close
End With
Set rs = Nothing
Set db = Nothing
' Force the form to refresh itself
' This will cause the Form's OnCurrent event to be triggered
Me.Requery
End Sub

How can I populate combo box from a database query?

I want to populate a combo box with the results of a query in Access. I'm just not seeing how to do it. As far as I understand, one must first create a record set, read the query results into the record set, then write the record set to the combo box's row source property. Is this correct? is there a simple example somewhere that I can follow? I haven't found one in any of the other threads.
Here's my attempt so far:
Dim RS As Recordset
Dim myDB As Database
Set RS = myDB.OpenRecordset("SourcesNotDisposed", dbOpenDynaset)
Do While Not RS.EOF
With Me.cmbSN
RowSource.AddItem
End With
Loop
With this code, I'm getting an "Object required" error at the RowSource line. cmbSN has data properties:
Row source Type = Table/Query
Bound Column = 0
Limit to List = Yes
Allow value list edits = Yes
Inherit value list = Yes
Show only row source = No
The query only has one visible column called "Serial Number"
Thanks in advance
Thanks for all the suggestions everyone. I've worked it out and found a very simple solution. With the combo box's Row Source Type property set to Table/Query, all I needed to do was set the Row Source property to a valid SQL string. e.g.:
strSQL = "SELECT Sources.[Serial Number] FROM Sources " & _
"WHERE (((Sources.Nuclide)='Cf-252') " & _
"AND ((Sources.[Location / Status])<>'Disposed')) " & _
"ORDER BY Sources.[Serial Number];"
Me.cmbItem.RowSource = strSQL
Me.cmbItem.Requery
Below code insert table fields into combo box. Add this code under onEnter event of combo
Private Sub CM_Enter()
'CM is combobox name
Dim strItem1 As String
Dim strItem2 As String
On Error Resume Next
Dim i As Integer 'Index for loop
With Me.CM
.RowSourceType = "Value List" 'Set rowsource type as Value list
.RowSource = "" 'Clean combo contents
End With
'Loop through field names of table and add them to your combo:
For i = 1 To CurrentDb.TableDefs("table1").Fields.Count - 1
Me.CM.AddItem (CurrentDb.TableDefs("table1").Fields(i - 1).Name)
Next i
'/***Delete unwanted items from the combo
strItem1 = "col1"
strItem2 = "col2"
'CM.RemoveItem strItem1
'CM.RemoveItem strItem2
End Sub
I think you might need to do a 'first read a record' before starting the loop.
Try using a RS.MoveFirst before the Do-While loop?
I think you may also need to do a .MoveNext inside your loop, just before the Loop statement; it's been a long while since I did anything like this in VBA, but it looks to me like it'll just add the same item over and over until it runs out of memory? I don't think the AddItem moves the record pointer to the next record by itself.
You may also need to check what happens if you MoveNext off the end of the record set...
HTH :)