Access. How to Create a record and select that record in CBO on another form? - vba

I have two forms frmProductCreate and frmColourCreate.
In frmProductCreate I have:
Combobox: colourID
Button: btnColCreate
The idea is that if a user needs to create a new colour, they can click on the create button which opens frmColourCreate, name the new colour and click save button. Which will save the new colour in the colours table (which is the record source for the cbo ColourID in frmProductCreate). Then requery colourID in frmProductCreate and close frmColourCreate.
What I also want this save button to do is after the requery to select the cbo colourID and go to the last created colour. i.e. the last record. I have tried a few codes but failed to make it work. Any help will be greatly appreciated.
Private Sub btnSavecol_Click()
Dim cancel As Integer
If Me.ColName = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
cancel = True
Else
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then
cancel = True
Else
CurrentDb.Execute " INSERT INTO Colours (ColName) VALUES ('" & Me.ColName & "')"
Me.ColName = ""
DoCmd.Close
If CurrentProject.AllForms("frmProductCreate").IsLoaded = False Then
cancel = True
Else
Forms!frmproductCreate!ColourID.Requery
'Forms!frmproductCreate!ColourID.SetFocus
'Forms!frmproductCreate!ColourID.items.Count = -1
'Forms!frmproductCreate!ColourID.Selected(Forms!frmproductCreate!ColourID.Count - 1) = False
'YourListBox.SetFocus
'YourListBox.ListIndex = YourListBox.ListCount - 1
'YourListBox.Selected(YourListBox.ListCount - 1) = False
End If
If CurrentProject.AllForms("frmProductDetails").IsLoaded = False Then
cancel = True
Else
Forms!frmproductDetails!ColourID.Requery
End If
End If
End If
End Sub

Some remarks:
Whatfor is the variable cancel? Because it is not used, I removed it.
I have no really idea whatfor you need Me.ColName = "".
Why do you close the current form so early? I moved DoCmd.Close to the end.
I made your code a bit more readable, by removing 'arrow-code' (those nested IFs).
Finally try this:
Private Sub btnSavecol_Click()
If Me.ColName.Value = "" Then
MsgBox "You must enter a Colour Name."
DoCmd.GoToControl "ColName"
Exit Sub
End If
If MsgBox("Are you sure you want to create new Colour?", vbYesNo) = vbNo Then Exit Sub
CurrentDb.Execute "INSERT INTO Colours (ColName) VALUES ('" & Me.ColName.Value & "')"
If Not CurrentProject.AllForms("frmProductCreate").IsLoaded Then GoTo Done
Forms!frmproductCreate!ColourID.Requery
'This sets the ComboBox 'ColourID' to the new colour:
'Forms!frmproductCreate!ColourID.Value = Me.ColName.Value
'If you use an automatic generated ID in the table 'Colours', then you will have to get that ID from the color and set it to the ComboBox:
Forms!frmproductCreate!ColourID.Value = DLookup("ColID", "Colours", "ColName = '" & Me.ColName.Value & "'")
Me.ColName.Value = ""
If Not CurrentProject.AllForms("frmProductDetails").IsLoaded Then GoTo Done
Forms!frmproductDetails!ColourID.Requery
Done:
DoCmd.Close
End Sub

Related

Close subform, remove main form filter and go back to original record

I am opening a subform from my main form to allow data to be changed. Once the changes are made, I want to pass the data back to the main form. remove the filter, and go back to the original record. I have the Primary Key in the subform so I am passing it back. I used some code from another user's but it did not work not is my code. Any thoughts?
Private Sub cmd_close_Click()
Dim result As String
Dim ID As Variant
result = MsgBox("Save Geo Location?", vbOKCancel, "Save Geo Location")
If result = vbOK Then
Forms!frm_acct_select!GeoLoc_X = Me.txt_GeoLocX
Forms!frm_acct_select!GeoLoc_Y = Me.txt_GeoLocY
Forms!frm_acct_select.FilterOn = False
'this code fails immediately
With frm_acct_select.Form
ID = Me.txt_ParentID.Value
.FilterOn = False
.Recordset.FindFirst "ParentAccountID=" & ID
End With
'this code fails type mismatch criteria at the recordset.findfirst line
' With Forms!frm_acct_select
' ID = Me.txt_ParentID.Value
' .FilterOn = False
' .Recordset.FindFirst "ParentAccountID = " & ID
' End With
DoCmd.Close acForm, "sfrm_geoloc_update", acSaveNo
Else
DoCmd.Close acForm, "sfrm_acct_select_search", acSaveNo
End If
End Sub
Apparently, I still need to work on my string formatting.
Declaring ID as String was correct however I needed to add quotes to my code.
.Recordset.FindFirst "ParentAccountID = '" & ID & "'"

The blank column of the particular List Box based on query is not recognized as either empty or null

The Listbox: SearchList get data from the query: Machine_Search.So how it works is i input my Serial Number into the Search textbox and press the button search then select the record displayed on the SearchList. When the record is selected, i then press edit. The condition is that if the record that i search using Serial Number have empty field in the End_Date it will go on smoothly. However if the record that is search using Serial Number have a date in the End_Date it will prompt a msgbox and, close and open the form again. The issue lies at where it cannot detect if End_Date is null or empty and will prompt the msgbox regardless of the condition.
Table: Machine
Query: Machine_Search - It query the table:Machine where there is a form called: Machine_Load which fills half the field in the table and the other will be filled by Machine_Unload/
Form:Machine_Unload
Is there a way to solve this issue?
Private Sub cmdSearch_Click()
Dim check As String
DoCmd.OpenQuery "Machine_Search"
DoCmd.Close acQuery, "Machine_Search"
SearchList.Requery
If SearchList.ListCount = 0 Then
MsgBox ("No records found.")
DoCmd.Close
DoCmd.OpenForm "Machine_Unload"
Exit Sub
End If
Me.cmdEdit.Enabled = True
Me.cmdSearch.Enabled = False
Me.txtSN.Enabled = True
Me.txtDate.Enabled = True
Me.txtTime.Enabled = True
Me.CheckTime.Enabled = True
Me.ListSuccess.Enabled = True
Me.txtOperator.Enabled = True
Me.txtRemarks.Enabled = True
Me.txtSearch.Enabled = False
Me.txtSN.SetFocus
End Sub
Private Sub cmdEdit_Click()
On Error GoTo Err_cmdEdit_Click
Dim SN_Value As String
Dim Date_Value As String
If Me.SearchList.ListIndex > -1 Then
SN_Value = Me.SearchList.Value
Date_Value = Me.SearchList.Column(5)
If Not IsEmpty(Date_Value) Then
MsgBox ("The Unload data for this Serial Number have been filled, Please confirm with cell leader.")
DoCmd.Close
DoCmd.OpenForm "Esagon_Unload"
Exit Sub
End If
End If
'check whether there exists data in list
If Not (Me.SearchList.Recordset.EOF And Me.SearchList.Recordset.BOF) Then
'get data to text box control
With Me.SearchList.Recordset
Me.txtSN = .Fields("Serial_Number")
'store id of serial number in tag of txtSN in case id is modified
Me.txtSN.Tag = .Fields("Serial_Number")
'Disable button edit
Me.cmdEdit.Enabled = False
Me.cmdUpdate.Enabled = True
End With
End If
End_Err:
Exit Sub
Err_cmdEdit_Click:
MsgBox ("Select the Serial Number." & vbCrLf & "Please try again and click on the Serial Number below.")
DoCmd.Close
DoCmd.OpenForm "Machine_Unload"
Resume End_Err
End Sub
SELECT Machine.Serial_Number, Machine.End_Date, Machine.End_Time, Machine.End_System_Time, Machine.End_Operator, Machine.Success, Machine.End_Remarks
FROM Machine
WHERE (((Machine.Serial_Number)=[Forms]![Machine_Unload]![txtSearch]));
IsEmpty is not for this usage. Try:
If Not IsNull(Date_Value) Then
or:
If Nz(Date_Value) <> "" Then

Filtering data on form causes combo box to not function

I have a form that displays student records.
I have a combobox that allows you to select a student.
Finally, I have two buttons for filtering. One filters on all Students the other only active Students.
Two Issues which I beleive are related.
One, when the form loads the cbo does NOT work.
Two, if I select the "All Students" button the cbo works. When I select the "Active Students" button the cbo does NOT work again.
Form Record Source:
Select tblStudents.*
Form Load:
Private Sub cmdStudent_Click()
On Error GoTo cmdStudent_Click_Err
DoCmd.OpenForm "frmStudents", acNormal, "", "[Last3]=" & "'" & "Sanders
862" & "'", , acNormal
cmdStudent_Click_Exit:
Exit Sub
cmdStudent_Click_Err:
MsgBox Error$
Resume cmdStudent_Click_Exit
End Sub
ComboBox Code:
Private Sub cboFindRecord_AfterUpdate()
' Find the record that matches the control.
Dim rs As Recordset
Set rs = Me.RecordsetClone
rs.FindFirst "[SN] = '" & Me![cboFindRecord] & "'"
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
End Sub
All Students Button:
Private Sub cmdAllStudents_Click()
cmdAllStudents.ForeColor = 16777215
cmdAllStudents.BackColor = 16711680
cmdAllStudents.FontBold = True
cmdActiveStudents.ForeColor = 0
cmdActiveStudents.BackColor = 16777215
cmdActiveStudents.FontBold = False
Me.FilterOn = False
cboFindRecord.RowSourceType = "Table/Query"
cboFindRecord.RowSource = "SELECT tblStudents.SN, tblStudents.Last3 FROM
tblStudents ORDER BY tblStudents.Last3;"
cboFindRecord.Requery
Call cboFindRecord_AfterUpdate
cboFindRecord.SetFocus
End Sub
Active Student Button:
Private Sub cmdActiveStudents_Click()
cmdActiveStudents.ForeColor = 16777215
cmdActiveStudents.BackColor = 16711680
cmdActiveStudents.FontBold = True
cmdAllStudents.ForeColor = 0
cmdAllStudents.BackColor = 16777215
cmdAllStudents.FontBold = False
Me.FilterOn = True
cboFindRecord.RowSourceType = "Table/Query"
cboFindRecord.RowSource = "SELECT tblStudents.SN, tblStudents.Last3,
tblStudents.Status_ID FROM tblStudents WHERE (((tblStudents.Status_ID) Not
In (6,7))) ORDER BY tblStudents.Last3;"
cboFindRecord.Requery
Call cboFindRecord_AfterUpdate
cboFindRecord.SetFocus
End Sub
Thank you for any assistance.
I have tried modifying the record set to match all or active students with no change.
OK, not sure why this is happening but I have fixed my issue. The problem is with the form loading code.
When I was loading the Student from from another form, I had it load our test student by default. My theory is that this was changing the record-set. I would appreciate an explanation if someone knows.
I removed forcing the student record when loading the student form and put the code in the On Load event for the form.

Me.Dirty moves currently selected record

I have an Access 2007 form that's giving me some headache.
I have a list of records that start as a combo box to pick a company and then a series of checkboxes to indicate the company's role.
If the user needs to add a new company, they'd pick the company name from the combo box, and then click the checkbox that indicates what role the company is playing. When the checkbox is checked, the form follows the following code to show a popup that captures additional information:
Private Sub chkOperationsAndMaintenance_AfterUpdate()
'DoCmd.RunCommand acCmdSaveRecord'
If Me.Dirty Then Me.Dirty = False
If chkOperationsAndMaintenance.Value = True Then
DoCmd.OpenForm "OmPopupForm", , , "CompanyProjectId = " & Me.CompanyProjectID, , acDialog
Me.Requery
End If
End Sub
This code will save the record on the CompanyProject table to create the row. It then pulls the CompanyProjectID (PK of the CompanyProject table) so it knows which ID to feed the popup.
The issue I'm having is that on the Me.Dirty line (and also the above commented-out acCmdSaveRecord), the entire form saves and refreshes, moving the selected row to the first record (in this case, "Gamesa") rather than the newly entered record. So the ensuing popup is fed the CompanyProjectID of the first record rather than the newly-entered record, and it also reads the "checked" state of the checkbox from the first record rather than the one upon which the user is working.
I doctored the code to look like this:
Private Sub chkOperationsAndMaintenance_AfterUpdate()
Dim CPID As Long
Dim CID As Long
Dim rs As Recordset
Set rs = Me.RecordsetClone
CID = Me.CompanyID
'DoCmd.RunCommand acCmdSaveRecord'
If Me.Dirty Then Me.Dirty = False
CPID = DLookup("MAX(CompanyProjectID)", "CompanyProject", "cpProjectID = " & Me.cpProjectID & _
" AND CompanyID = " & CID)
rs.Find "[CompanyProjectID] = " & CPID
Me.Bookmark = rs.Bookmark
If chkOperationsAndMaintenance.Value = True Then
DoCmd.OpenForm "OmPopupForm", , , "CompanyProjectId = " & Me.CompanyProjectID, , acDialog
Me.Requery
End If
End Sub
The idea with these alterations is that we'll get the FK from the parent form ("cpProjectID") and the CompanyID of the selection from the combobox, then save the record. Once the record is saved, we have the CompanyProjectID already stored, so then the rs.Find and Me.Bookmark lines will then select the record that matches that CompanyProjectID.
This sometimes works, and sometimes doesn't. Generally doesn't. In this case, I refreshed the parent form and the current form and attempted to add a new company and then click the "Owner" checkbox (which uses the same code as above, just a different checkbox ID) to see the Bookmark on the wrong row:
At this point, I'm not sure what to do. If I don't save the record (via acCmdSaveRecord or Me.Dirty=False) then I don't have a CompanyProjectID to send as the input parameter for the ensuing popup, but if I do save the record, then the form changes the record and the wrong parameter is sent and the wrong checkbox's checked state is read. I can't just use an arbitrary index to work off of (such as acNewRec), as the user might need to edit an existing row instead of adding a new one.
I tried the method in this post already: MS Access how to Update current row, move to next record, not first, but the find/bookmark isn't consistently working.
EDIT (12/15/2014)
I ended up going with the following VBA code:
Private Sub chkOperationsAndMaintenance_AfterUpdate()
Dim CPID As Long
Dim CID As Long
Dim rs As Recordset
Set rs = Me.RecordsetClone
CID = Me.CompanyID
If Me.Dirty Then Me.Dirty = False
CPID = DLookup("MAX(CompanyProjectID)", "CompanyProject", "cpProjectID = " & Me.cpProjectID & _
" AND CompanyID = " & CID)
Do While Me.CompanyProjectID <> CPID
If Me.CurrentRecord < Me.Recordset.RecordCount Then
DoCmd.GoToRecord , , acNext
Else
DoCmd.GoToRecord , , acFirst
End If
Loop
If chkOperationsAndMaintenance.Value = True Then
DoCmd.OpenForm "OmPopupForm", , , "CompanyProjectId = " & Me.CompanyProjectID, , acDialog
Me.Requery
End If
End Sub
I feel like there has to be a better answer for this, but this is appearing to work right now. I have my end user/lab rat testing it at the moment, so I'll mark this complete if this pans out. I still think there has to be a better solution for this, but at the moment, this solution is able to capture the requisite ID to pass to the popup, and it selects the appropriate row after this ID is captured.
Have you considered saving the current position - like Me.CurrentRecord, then after the save reposition to the desired record. As an example, you could add a 'Before' or 'After' Insert to save the position, then later reposition. See the following:
Option Compare Database
Option Explicit
Dim lCurRec As Long
Private Sub Form_AfterInsert()
lCurRec = Me.CurrentRecord
Debug.Print "After Insert, Current: " & Me.CurrentRecord
End Sub
<<< YOUR SUB>>>
DoCmd.GoToRecord acDataForm, Me.Name, acGoTo, lCurRec
This code will work when adding a new record as well as when editing an existing record:
Private Sub chkOperationsAndMaintenance_AfterUpdate()
Dim c As Long
Me.Dirty = False
If chkOperationsAndMaintenance Then
DoCmd.OpenForm "OmPopupForm", , , "CompanyProjectId = " & Me.CompanyProjectID, , acDialog
c = Me.CurrentRecord
Me.Requery
DoCmd.GoToRecord , , acGoTo, c
End If
End Sub
I am guessing that your popup form does things that are specific to Operations & Maintenance, and does not change the values of any of the checkboxes on the main form. If this is the case, you don't need a Requery at all, and the code can be simplified:
Private Sub chkOperationsAndMaintenance_AfterUpdate()
Me.Dirty = False
If chkOperationsAndMaintenance Then
DoCmd.OpenForm "OmPopupForm", , , "CompanyProjectId = " & Me.CompanyProjectID, , acDialog
End If
End Sub

MS Access, DoEvents to exit loop

What I'd like to accomplish:
Do While ctr < List and Break = False
code that works here...
DoEvents
If KeyDown = vbKeyQ
Break = True
End If
loop
Break out of a loop by holding down a key (eg, Q). I've read up on DoEvents during the loop in order to achieve the functionality that I want. The idea is to have a Do While loop run until either the end of the list is reached or when Q is held down. I'm having issues getting the code to work the way I want, so I'm reaching out to hopefully end the frustration. My experience with VBA is very limited.
UPDATE - More code to expose where the problem might be. This is all in the order I have it (in case order of subs makes a difference:
Private Sub Form_KeyPress(KeyAscii As Integer)
Dim strChar As String
strChar = UCase(Chr(KeyAscii))
If strChar = "Q" Then
blnQuit = True
Debug.Print "Q pressed"
End If
End Sub
Private Sub Master_Report_Click()
Dim i As Integer
Dim Deptarray
blnQuit= False
If IsNull(Me.Hospital) Then
MsgBox ("Please Choose a Hospital")
Else
DoCmd.OpenForm "Report Print/Update", acNormal, , , , acDialog
If Report_choice = "Current_List" Then
Debug.Print "Create master rec report"
DoCmd.OpenReport "Master Rec Report", acViewPreview
DoCmd.RunCommand acCmdZoom100
ElseIf Report_choice = "Update_All" Then
total = (DCM_Dept.ListCount - 1)
ctr = 1
Do While ctr < (DCM_Dept.ListCount) And LoopBreak = False
Debug.Print "LoopBreak: "; LoopBreak
Debug.Print "Counter: "; ctr
DCM_Dept.Value = DCM_Dept.Column(0, ctr)
Update_Site (Me.Hospital)
ctr = ctr + 1
'DoEvents
' If vbKeyQ = True Then
'LoopBreak = True
'End If
Loop
Debug.Print "Update loop exited"
Debug.Print "Create master rec report"
DoCmd.OpenReport "Master Rec Report", acViewPreview
DoCmd.RunCommand acCmdZoom100
Else
End If
End If
End Sub
Private Sub Update_Site(Site As String)
If IsNull(Me.Hospital) Then
MsgBox ("Please Choose a Hospital")
ElseIf IsNull(Me.DCM_Dept) Then
MsgBox ("Please Choose a Department")
ElseIf Site = "FORES" Then
Debug.Print "Run FORES update macro"
DoCmd.RunMacro "0 FORES Master Add/Update"
ElseIf Site = "SSIUH" Then
Debug.Print "Run SSIUH update macro"
DoCmd.RunMacro "0 SSIUH Master Add/Update"
End If
End Sub
Report_choice and LoopBreak are both Public variables. My original idea was to have a popup form floating over the main form to display a counter ("Processing department X of Y") and a button to break the loop on there. I realized that the form was unresponsive while the Update_Site() was running its macro so I decided to go with holding a key down instead.
So, where do I go from here to get OnKeyDown to work? Or, is there a better way to do it?
Try to set the Key Preview of the form to Yes and add a variable blnQuit and a key press event in your form like this:
Private blnQuit As Boolean
'form
Private Sub Form_KeyPress(KeyAscii As Integer)
Dim strChar As String
strChar = UCase(Chr(KeyAscii))
If strChar = "Q" Then
blnQuit = True
End If
End Sub
Then check the blnQuit in your Do While condition, like this:
blnQuit = False
Do While ctr < List And Not blnQuit
code that works here...
DoEvents
loop