MS ACCESS COMBOBOX - ms-access

good day!
i am using ms access and i want to know what will i do if i have 5 comboboxes in my form then 10 choices of name which connect in one table, how can make that if ever i select one of the name in list then the selected list will not show on the 2nd combobox list. there are 5 comboboxes in my list. look like this

Consider switching to value list and add the items the boxes using a query in VBA. Then delete and add items from other boxes when a change is made.
Option Explicit
' Have to use global variables because combobox.oldValue is not reliable
Dim strOld1 As String
Dim strOld2 As String
Dim strOld3 As String
Dim strOld4 As String
Dim strOld5 As String
Private Sub frmMain_Load()
Dim rsNames as Recordset
' Get names
Set rsNames = CurrentDB.OpenRecordset( _
"SELECT [Names] " & _
"FROM tblPerson")
' Setup recordset
If rsNames.RecordCount > 0 Then
rsNames.MoveLast
rsNames.MoveFirst
' Add names to all boxes
Do While Not rsNames.EOF
cboNames1.addItem rsNames.Field("Name")
cboNames2.addItem rsNames.Field("Name")
cboNames3.addItem rsNames.Field("Name")
cboNames4.addItem rsNames.Field("Name")
cboNames5.addItem rsNames.Field("Name")
rsNames.MoveNext
End If
' Dispose recordset asap
Set rsNames = Nothing
End Sub
Private Sub addRemoveItem(ByRef thisCombo As Variant, ByRef oldValue As String)
Dim arrCombos(1 To 5) As ComboBox
Dim otherCombo As Variant
Dim intIndex As Integer
' Get a list of all combo boxes
Set arrCombos(1) = Me.cboNames1
Set arrCombos(2) = Me.cboNames2
Set arrCombos(3) = Me.cboNames3
Set arrCombos(4) = Me.cboNames4
Set arrCombos(5) = Me.cboNames5
' Check for comboboxes that are not the one changed
For Each otherCombo in arrCombos
If otherCombo.ControlName <> thisCombo.ControlName Then
' Search for exisitng item
IntIndex = 0
Do While otherCombo.itemData(intIndex) <> thisCombo.Value _
And intIndex < otherCombo.ListCount
intIndex = intIndex + 1
Loop
' Remove the found item
otherCombo.removeItem intIndex
' Add unselected value back
If oldValue <> "" Then
otherCombo.addItem oldValue
End if
Next
' Change the old value to the new one
oldValue = thisCombo.Value
End Sub
Private Sub cboName1_Change()
RemoveAddItem Me.cboName1, strOld1
End Sub
Private Sub cboName2_Change()
RemoveAddItem Me.cboName2, strOld2
End Sub
Private Sub cboName3_Change()
RemoveAddItem Me.cboName3, strOld3
End Sub
Private Sub cboName4_Change()
RemoveAddItem Me.cboName4, strOld4
End Sub
Private Sub cboName5_Change()
RemoveAddItem Me.cboName5, strOld5
End Sub
Sorry, I did this on a phone...

Related

Setting Combobox Value With VBA MS Access

I am trying to make a module to pass a single result of a query into a Combobox to be populated/displayed immediately on Form_Load event, but I keep getting the following error: Run-time error '2465' "Microsoft Access can't find the field 'MyCombo' referred to in your expression"
Query result is tested and returning the proper value. the problem is in the reference call to the MyCombo combobox.
This is my code below:
Public Function getSetRefNo() As String
Dim rs1 As DAO.Recordset
Dim currentformName As String
currentformName = Screen.ActiveForm.Name
Dim docidrefnoquery As String
Dim dociddefaultvalue As String
Set rs1 = CurrentDb.OpenRecordset("SELECT DISTINCT ColA FROM TblA WHERE ColC = " & Forms(currentformName)![Combo25])
Do Until rs1.EOF = True
docidrefnoquery = rs1(0)
rs1.MoveNext
Loop
rs1.Close
Set rs1 = Nothing
dociddefaultvalue = DLookup("RefNo", docidrefnoquery) 'RefNo here is the target column in the Query
Forms(currentformName)![MyCombo] = dociddefaultvalue 'MyCombo here is the Combobox Name
Debug.Print docidrefnoquery & " - " & dociddefaultvalue
End Function
on the targeted form, I use this code:
Private Sub Form_Load()
Call getSetRefNo
End Sub
after opening the targeted form, I receive the above mentioned error. I don't know what's wrong I tried to trace everything and it seems to be fine, I used the same chunk of codes in other places and worked fine. don't know what's wrong here to be honest. I would be grateful if you could help me elaborate what's going on.
I had to alter the form_load event like the following:
Private Sub Form_Load()
Me.TimerInterval = 30
End Sub
Private Sub Form_Timer()
Me.TimerInterval = 0
Call getSetRefNo
End Sub

not able to update access table field using VBA

I have a userform in access which submits the data to a table, there are two fields in table which I want to get populated automatically whenever user makes a new entry in form. I am using the below vba code with that form :
Option Compare Database
Public Function GetUserName() As String
Dim obj1 As Object
Set obj1 = CreateObject("WScript.Network")
GetUserName = DLookup("[BAFUser]", "BAF_User", "[BRID] = '" & obj1.UserName & "'")
Set obj1 = Nothing
End Function
Private Sub Form_BeforeInsert(Cancel As Integer)
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
End Sub
Private Sub Form_Load()
Me.DataForm.Form.Recordset.MoveLast
End Sub
Private Sub SaveBtn_Click()
RunCommand acCmdSaveRecord
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
End Sub
I am able to get the value in "owner" field but not in "AdvisorName" field.
What can be the possible reason behind this ?
is there any mistake in my code or is there any better method of doing this ?
The below code should commit both values to your table using a querydef. This is my preferred approach but there are other ways to do it as well. The qdf represents a sql string that can accept parameters from code. We are inserting the values of our variables directly into the sql string.
I copied the code from the save button to re-establish the form state after entry. This should bring the last record back up, but it will depend on the cursortype of the recordset whether the saved record is represented or not (it might go backwards).
Private Sub Form_BeforeInsert(Cancel As Integer)
Dim qdf As QueryDef
Dim Owner2 As String
Dim AdvisorName As String
Owner2 = CreateObject("WScript.Network").UserName
AdvisorName = GetUserName
Set qdf = CurrentDb.CreateQueryDef("", "INSERT INTO Mau_con (Owner, AdvisorName) VALUES ('" & Owner2 & "', '" & AdvisorName & "')")
qdf.Execute
Me.Requery
Me.DataForm.Form.Recordset.MoveLast
Set qdf = Nothing
End Sub

Access 2010 - Error Handling Filter Subform

how can I disable the filter of a Datagridview, using VBA, if after filtering there is no record?
Here my first try:
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
If Me.RecordsetClone.RecordCount = 0 Then
MsgBox ("Kein Datensatz gefunden. Filter wird entfernt.")
Me.Form.FilterOn = False
Me.Form.Requery
End If
End Sub
Here is the second try:
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
Dim rs As DAO.Recordset
Set rs = Me.RecordsetClone
rs.Filter = Replace(Me.Filter, "[Tabelle1].", "")
Set rs = rs.OpenRecordset()
If rs.EOF Then
Cancel = True
End If
End Sub
In the second code I get the error 3061. The first code "works", but is finally not want I need.
Because:
I have 3 Forms. MAIN, Sub1 and Sub2.
In the MAIN are Sub1 , Sub2 and a single TextBox. The TextBox is call "psoudoID". Sub1 is a normal Form to show the details of the different recordsets and is placed on the top of the MAIN. Below Sub1 is Sub2. Sub2 is a Datagridview. When the user is clicking on a recordset on Sub2, the ID from Sub2 "goes" to the psoudoID and from there to Sub1. You understand?
Now is the problem, that the user can filter every column in Datagrid to find the recordset here needs and show all details above. But when the datagrid is empty after filtering , so Sub2 can't give an ID to the psoudoID and so on Sub1 is not displayed in MAIN much longer. The screen is empty on that place. By clicking the Filter-Button in grid, Sub1 is on the screen again.
I want to disable the filter by clicking "Ok" of a MsgBox or automatically and not by clicking the Filter-Button on gridview.
I hope you can understand my discribtion. And sorry for my bad English :-)
THX.
Vegeta
I believe you're having problems with filters being Null, and with using Me.Filter before the filter is actually applied. Also, re-assigning an object to a property/member of itself has caused problems for me before, so I try to avoid doing that.
The following should work:
Dim strOldFilter As String
Private Sub Form_ApplyFilter(Cancel As Integer, ApplyType As Integer)
Me.TimerInterval = 50
strOldFilter = Nz(Me.Filter, "")
End Sub
Private Sub Form_Timer
Me.TimerInterval = 0
If Me.Filter = strOldFilter Then Exit Sub
Dim rs As DAO.Recordset
Dim strFilter As String
strFilter = Nz(Me.Filter, "")
If strFilter = "" Then
'Handle this specific scenario
Exit Sub
End if
Set rs = Me.RecordsetClone
rs.Filter = Replace(strFilter, "[Tabelle1].", "")
Dim rsf as DAO.Recordset
Set rsf = rs.OpenRecordset
If rsf.EOF Then
Me.Filter = strOldFilter
End If
End Sub
Note the potential to cause infinite loops that repeat every 50 msec if you change a filter resulting in 0 records to another filter resulting in 0 records (but you shouldn't be able to have a filter resulting in 0 records if the function works)

search sub form from text box in form

I have a form (frm_main)
and i have a subform on this form (frm_weblogs_subform)
I am trying to search the subform using a text box.
the code i've found and have been playing with to no avail is:
Private Sub find_weblog_button_Click()
Dim D As Database
Dim wlog As DAO.Recordset
Dim Criteria As String
Set D = CurrentDb
Set wlog = D.OpenRecordset("form_frm_weblogs_subform", dbOpenDynaset)
Criteria = "[weblog_number]='" & [weblogSearch] & "'"
wlog.FindFirst Criteria
wlog.Close
End Sub
It doesn't seem to register the form at all it keeps saying it can't be found.
can anyone help point me in the right direction?
It should read:
Dim wlog As DAO.Recordset
Dim Criteria As String
Set wlog = Me!<NameOfTheSubformCONTROL>.RecordsetClone
If wlog.RecordCount > 0 Then
Criteria = "[weblog_number]='" & [weblogSearch] & "'"
wlog.FindFirst Criteria
If wlog.NoMatch = False
' Found.
Else
' Not found.
End If
End If
wlog.Close
Replace <NameOfTheSubformCONTROL> with that, not the name of the subform.

Can I wrap an Access form with a transaction?

I want to make a form the essentially creates an invoice, but using some other related data as inputs or limits; In the process of adding items to the invoice, I need to reduce the items in another table. Since the user will enter several items at a time, I'd like to issue a "START TRANSACTION" when the form loads, and then do a "COMMIT" when the form updates. Thus, if they cancel the form, the other related tables (shown via subforms) would roll back to the previous values.
Can't be done using bound forms. You could use temporary tables to store the data and then update the main tables. A bit of a kludge but I've done that in the past.
See the TempTables.MDB page at my website which illustrates how to use a temporary MDB in your app.
Yes it can be done, to take control over the transaction in the form you need use this code:
Private Sub Form_Open(Cancel As Integer)
Set Me.Recordset = CurrentDb.OpenRecordset("NAME_OF_YOUR_TABLE_OR_QUERY")
End Sub
After that, you can use DBEngine to control the transaction.
It work for me (Im using Access 2007)
Note: If you insert a new record using the form interface it is visible when the Form_AfterInsert event is raised, therefore you can use DbEngine.Rollback in that event to undo the changes.
I have figured it out its possible to have it on bound forms. Everything you need to assign variable that contain an ID number on change event of any of the parent control. Than you need to transmit that ID value into the subform connected field and perform transaction on both forms the primary and the subform. Here is the example of how I did it.
Primary Form VBA
Option Compare Database
Option Explicit
Private boolFrmDirty As Boolean
Private boolFrmSaved As Boolean
Private Sub EmpolyeesID_Change()
Dim ordID As Integer
Dim subFormOrdID As Object
Set subFormOrdID = Forms!Order.OrderInstallation.Form!OrderID
ordID = Me.Form!OrderID
subFormOrdID.DefaultValue = ordID
End Sub
Private Sub Form_AfterDelConfirm(Status As Integer)
If Me.Saved = False Then Me.Saved = (Status = acDeleteOK)
End Sub
Private Sub Form_AfterUpdate()
Me.Saved = True
End Sub
Private Sub Form_Delete(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
'Check if form has got new values in it
Private Sub Form_Dirty(Cancel As Integer)
If Me.Dirtied = False Then DBEngine.BeginTrans
Me.Dirtied = True
End Sub
'Open Form as a Record Set and set the variables for it
Private Sub Form_Open(Cancel As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM Orders", dbOpenDynaset, dbAppendOnly)
Set Me.Recordset = rs
End Sub
Private Sub Form_Unload(Cancel As Integer)
Dim msg As Integer
If Me.Saved Then
msg = MsgBox("Do you want to commit all changes?", vbYesNoCancel)
Select Case msg
Case vbYes
DBEngine.CommitTrans
Case vbNo
DBEngine.Rollback
Case vbCancel
Cancel = True
End Select
Else
If Me.Dirtied Then DBEngine.Rollback
End If
End Sub
Public Property Get Dirtied() As Boolean
Dirtied = boolFrmDirty
End Property
Public Property Let Dirtied(boolFrmDirtyIn As Boolean)
boolFrmDirty = boolFrmDirtyIn
End Property
Public Property Get Saved() As Boolean
Saved = boolFrmSaved
End Property
Public Property Let Saved(boolFrmSavedIn As Boolean)
boolFrmSaved = boolFrmSavedIn
End Property
Private Sub ProductID_AfterUpdate()
'Calculations of VAT and Floor Price
Dim clcVAT As Integer
Dim sqlQry As String
Dim instID As Integer
instID = Me.Form!ProductID.Value
sqlQry = "SELECT Products.Price FROM Products WHERE Products.ProductID =" & instID & ""
Me.flPrice.RowSource = sqlQry
End Sub
Sub Form VBA
Option Compare Database
Option Explicit
'Transaction for sub-form
Private Sub Form_Open(Cancel As Integer)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT * FROM OrderInstallation")
Set Me.Recordset = rs
End Sub
Private Sub Form_AfterUpdate()
Dim emplID As Object
Dim cstmID As Object
Dim prdcID As Object
Dim DataArray As Variant
Dim RqrdFieldErorr As String
Dim qry As String
Set emplID = Me.Parent!EmpolyeesID
Set cstmID = Me.Parent!CustomerID
Set prdcID = Me.Parent!ProductID
If IsNull(emplID.Value) Or IsNull(cstmID.Value) Or IsNull(prdcID.Value) Then
MsgBox ("Please enter select required fields first")
Else
End If
End Sub
'Restrict updates of Installation subform if Employee, Customer and Product is not selected
Private Sub InstallationID_AfterUpdate()
Dim instID As Integer
Dim instPrice As Integer
Dim strQry As String
' Create query based on InstallationID value
instID = InstallationID.Value
strQry = "SELECT Installation.Price, Installation.InstallationID FROM Installation WHERE Installation.InstallationID =" & instID & ""
Me.Price.RowSource = strQry
End Sub