How to ensure selected combobox item is in table? (Access VBA) - vba

My goal is to create a way to log why something was changed and who changed it.
I have 2 comboboxes that are populated by tables. I use VBA to define the RowSource when the form opens.
When the user clicks the send button, before anything is changed, I want to make sure that the comboboxes have 'valid' selections.
One combobox is a list of employees based on firstname & ' ' & lastname
the other is a list of pre-set reasons (i.e. "Incorrect Hours", Wrong Item #", etc.)
If Nz(Me.cmbReason, "") = "" Then
fncMsgBox "Must select a reason from the dropdown for modifying a labor entry."
GoTo Exit_btnSend_Click
Else
If Not IsNull(DLookup("Reason", "tblEditReason", Me.cmbReason)) Then
fncMsgBox "Must select a reason from the dropdown for modifying a labor entry."
GoTo Exit_btnSend_Click
End If
End If
If Nz(Me.cmbModBy, "") = "" Then
fncMsgBox "Must enter who is modifying this labor entry."
GoTo Exit_btnSend_Click
Else
If IsNull(DLookup("FNAME & ' ' & LNAME", "EMP", Me.cmbModBy)) Then
fncMsgBox Me.cmbModBy & " is not a valid name."
GoTo Exit_btnSend_Click
End If
End If
When I have "If not IsNull..." then it won't accept anything regardless of valid or invalid, if I remove the "IsNull" then I get a mismatch debug.
How do I ensure that what the user puts inside the combo box, is in fact in the table?

June7 Comment - Maybe set combobox LimitToList property to Yes?
Resolved my problem.
LimitToList prevents anything not in the list from being accepted. When clicking on any other control in the form, it pops out the drop down until an item from the list is selected or it is left blank. Allowing the code I was using "If not IsNull(....." to do just what I was looking for!

Related

MS Access: Add attachment to record from Form field using VBA

I have a bounded form with property 'Data Entry = Yes' which has a multiple textboxes, and one field of type Attachment.
I have a "Save" button that prompts confirmation to save the record.
On the form I placed a checkbox labelled 'Includes training'.
If that checkbox is checked, I want to add to the same table, an additional record (other than the one added through the bounded form) with exactly the same information as the record inserted in the bounded form, except for one text field which will be different and defined in the VBA code.
I tried a CurrentDB.Execute SQL query but it does not work with the Attachment field type.
The solution proposed in the documentation doesn't apply to this case since I want to take the Attachment contained in the bounded Attachment field on the form and not from a path on disk.
I think something like the following could work, but when I test it, it saves the record from the bounded form, but not the additional one I want to add with the VBA code, AND it ends with the error:
424 Object Required
The VBA code:
Private Sub Form_BeforeUpdate(Cancel As Integer)
Dim ctl As Control
On Error GoTo Err_BeforeUpdate
If Me.Dirty Then
If MsgBox("Do you want to save the new record?", vbYesNo + vbQuestion, _
"Save Record") = vbNo Then
Me.Undo
MsgBox "Changes discarded."
Else
If Me.checkbox.Value = True Then
Set rsTable = db.OpenRecordset("Table")
With rsTable
.AddNew
!TextField1 = Me.TextField1.Value
!TextField2 = "My Own Text Field"
!AttachmentField = Me.AttachmentField.Value
.Update
.Bookmark = .LastModified
End With
MsgBox "Record was correctly saved."
End If
End If
End If
End Sub
Thanks a lot for any help.
EDIT:
So clearly this is not the right way to save a new record, but I need this record to be save AT THE SAME TIME (or just after) the one on the bounded form. I DON'T want the user to fill in another bounded form.
The reason for this is because what I am entering are language certification records, and there are certifications that are broader and include two levels.
Hence the checkbox signals "do you want to include the previous level as well?", if it is checked, then the PDF certificate uploaded will be valid both for level 1 and level 2.
All information will be the same except for the level name of the record.
I need these two to be separate records because I can also have them singularly and later I check conditions based on these individual language levels.
To use an attachment field you to use the special methods LoadFromFile to put an attachment in the DB and SaveFromFile to get the attachment back out of the DB. It looks like you attempted to assign a string to an attachment field.
I don't see where db is defined. Did you mean CurrentDb ?
The other problem I see is that you are using bang notation in a With block. Bang notation is a string lookup. If you want to call the item by name you would do so like this:
With CurrentDb.OpenRecordset("Table")
.AddNew
.Fields.Item("TextField1").Value = Me.TextField1.Value
.Fields.Item("TextField2").Value = "My Own Text Field"
.Fields.Item("AttachmentField").LoadFromFile Me.AttachmentField.FileName
.Update
.Bookmark = .LastModified
.Close
End With
The name of those Items must be correct.
I eventually solved this by creating a separate bounded from that pops up when I hit "Save" on the original bounded form if the checkbox is checked. There the user has the choice on whether to upload the same document as the original bounded form, or a different one.

Access Crashes When Using VBA To Set Bound Combobox RowSource

I've asked this on UA but wanted to post here as well in the hope someone can help me figure this out. Also, I'm aware of the evils of using MVFs; this is just something that I want to figure out.
I have a form with a combobox that is bound to a multivalue field. I want to use VBA to set the RowSource of the combobox. (Specifically, I want to use the value of another combobox on the form to filter the available choices in the second combobox, but right now I'm just trying to get the RowSource update to work with a static SQL statment.)
If I set the RowSource in the form's Design Mode, then it works as expected. But as soon as I try to use the exact same value to set the RowSource in VBA, Access crashes. Here is the code on the After Update event of the 'parent' combobox:
Private Sub cboSelRegSet_AfterUpdate()
Dim strSQL As String
On Error GoTo Query_Error
strSQL = "SELECT tblRegulation.ID, tblRegulation.RegulationCode " _
& "FROM tblRegulation " _
& "ORDER BY tblRegulation.RegulationCode;"
MsgBox "Before Filter", vbOKOnly
Me.cboSelReg.RowSource = strSQL
MsgBox "After Filter", vbOKOnly
Me.cboSelReg.Requery
MsgBox "After Requery", vbOKOnly
ExitNow:
Exit Sub
Query_Error:
MsgBox Err.Description
Resume ExitNow
End Sub
If I make "cboSelReg" unbound, then the update works, but since it is no longer bound to an MVF, the user can only select one value which defeats the purpose.
I've also added msgbox prompts to step through the code and it seems to get through the entire subroutine since I get the prompt after the requery. But as soon as I click OK, Access crashes.
Is there a way to make this work?

Run a Query Using a Button in Access

I am trying to run a query in Access 2010 inside of a form. The form, per user request, needs to have buttons that they can use to quickly change the data in their column. For the table being called, there are only two columns that matter: Equiptment_Name and Amount (The other several columns are just there to help reference the data in case they misspell the name of the product). The current query I have is:
UPDATE tblInventory SET Amount = Amount-[Enter Amount]
WHERE ((([tblInventory].Equiptment_Name)=[Enter Name]));
This works perfectly, I just can't get it to work in a form with a button. I've searched all over for help and was encouraged to use a macro because that would be the easiest way. Can someone please walk me through the process of getting a macro to run a version of my query? I'm fine with the user being prompted to enter the amount to withdraw from the Amount category, but it would be nice if they didn't have to type in the Equiptment_Name category since The button would be in the form next to it (see picture below). Thanks for all help in advance.
You could simply use VBA to get this going. Something along the lines of
Private Sub Command70_Click()
If Len(Me.AmountTextBoxName & vbNullString) = 0 Then
MsgBox "Amount cannot be empty !", vbCritical
Exit Sub
End If
If Len(Me.Equiptment_NameTextBoxName & vbNullString) = 0 Then
MsgBox "Equiptment Name cannot be empty !", vbCritical
Exit Sub
End If
CurrentDB.Exeucte "UPDATE tblInventory SET Amount = Amount - " & Me.AmountTextBoxName & _
"WHERE tblInventory.Equiptment_Name = '" & Me.Equiptment_NameTextBoxName & "';"
End Sub
I have taken the Equipment name is actually a String.

Add a Group E-mail command button to a Parameter Form in ms access 2010

I have an unbound parameter form based on a query called q_t_A.
Below you will see the code for the on click event of the command button cmdSendReport.
This attaches the report to a blank e-mail which allows me to choose the recipient.
I was wondering if I could add a cmdGroupSendReport button so that the report could be sent to a group of recipients.
In the underlying parameter form query q_t_A, I have a Yes/No field called EmailMailout, which singles out those who only want to have reports emailed to them.
I am planning on adding a checkbox parameter to the form chkEmailReportsOnly based on the Yes/No field EmailMailout so that if checked/true, only those email addresses will get the report sent to them by e-mail.
Is this the best way to do that? Secondly, how do I modify the code below so that All of the e-mail recipients receive the report shown in the combobox cboReports?
Private Sub cmdSendReport_Click()
If Not IsNull(cboReports) And cboReports <> "" Then
DoCmd.SendObject acSendReport, Me.cboReports, acFormatPDF
Elsed
MsgBox ("Please make a Report selection first from the drop down list to the left.")
cboReports.SetFocus
End If
cboReports = ""
End Sub
Thank you very much for your help...I am really new to this and so very thankful for your suggestions.
Oblio
Highlight 'SendObject' and click F1 to get Help. This object lets you add To, Cc, Bcc etc.
Loop through the records on your form, to create a string of email addresses to send To, eg:
Dim rs as recordset, s$
Set rs= Forms!chkEmailReportsOnly.RecordsetClone: With rs
While not .EOF
If !SendEmail then s = s & ";" & !Email
Wend
.close: End with
Set rs= nothing
s=mid(s,2)

Text box to have its value based on combo box value using a query

I have a single form on which there exists several combo boxes and text box. one combo box value (for the Wells) will be filled independently, then I needs the text box to have its value based on the value of the wells combo box value. I have created a query that solved the propblem partially, it requires parameter which the wells combo box value. If I ran with query a part from the form, it wroks good and asks for the parameter and it is OK. I do think to make use of VBA, adding a code which process a SELECT statement (of the query mentioned above), then to tell it to take its parameter from the wells combo value which will ready on the form.
Can someone help on this. Can this works as I descriped.
Thanks in advance.
Mohamed
Further to my question above, I have tried the following solution:
Private Sub Well_ID_Change()
Last_Ref.ControlSource = " SELECT TOP1 New_Ref FROM" & _
" BSW_Transactions WHERE BSW_Transactions.New_Ref Is Not Null AND BSW_Transactions.Well_ID = " & Me.Well_ID.Value & _
" ORDER BY BSW_Transactions.Sample_Date DESC"
End Sub
the Last_Ref is the text box I want to fill in with result of the embedded SELECT statement in the code. The Well_ID is the combo box which value will be the parameter of the SELECT statement. The Well_ID is number field and it displays the well_name and stores the associated ID value in the table. Upon running the form after saving changes, the Last_Ref text box showed (#Name?). I guessed that the text box (is a number field) found a text in the combo box Well_ID, so I added ".Value" to the above syntax at the criteria Me.Well_ID. However the problem still exists.
May I mistaken in the syntax, would someone help on this. Can this works fine?
Thanks in advance. Mohamed
The problem is that text boxes cannot have their control source set like a combo box or a list box, it needs to be passed the value e.g:
Private Sub Well_ID_Change()
Dim rs As Recordset
Set rs = CurrentDb.OpenRecordset("SELECT TOP1 [New_Ref] FROM" & _
" [BSW_Transactions] WHERE [BSW_Transactions].[New_Ref] Is Not Null" & _
" AND [BSW_Transactions].[Well_ID] = " & Me.Well_ID & _
" ORDER BY [BSW_Transactions].[Sample_Date] DESC", dbOpenSnapShot)
rs.MoveFirst
Last_Ref = rs![New_Ref]
rs.Close
Set rs = Nothing
End Sub
I've also dropped the .Value again from your combo box as its not required