BeforeUpdate Access VBA in form field can only enter number - vba

I have a form where I want either Asset or Location filled out and Supervisor or Lead or Crew or Work Group or Crew Work Group. I have the code and it works but it only allows me to enter numbers into these fields. I want to be able to enter numbers and letters into these fields.
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Form_frmAddPM.Asset Or Form_frmAddPM.Location) Then
MsgBox "Please enter a value in an asset or location."
Cancel = True
End If
If IsNull(Form_frmAddPM.Supervisor Or Form_frmAddPM.Lead Or
Form_frmAddPM.Crew Or Form_frmAddPM.Work_Group Or
Form_frmAddPM.Crew_Work_Group) Then
MsgBox "Please enter value in Supervisor, Lead, Crew, Work Group, or
Crew
Work Group."
Cancel = True
End If
End Sub
I have tried to change integer to different types. With the code above when I try to enter letters into the form a mismatch type error pops up.
Thank you in advance for your help.

You're using the bitwise OR operator, which requires both values you use it on to be an integer (see the docs, VB.Net but works the same in VBA)
Instead, you should check for each field if it's null separately:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Form_frmAddPM.Asset) Or IsNull(Form_frmAddPM.Location) Then
MsgBox "Please enter a value in an asset or location."
Cancel = True
End If
If IsNull(Form_frmAddPM.Supervisor) Or IsNull(Form_frmAddPM.Lead) Or
IsNull(Form_frmAddPM.Crew) Or IsNull(Form_frmAddPM.Work_Group) Or
IsNull(Form_frmAddPM.Crew_Work_Group) Then
MsgBox "Please enter value in Supervisor, Lead, Crew, Work Group, or
Crew
Work Group."
Cancel = True
End If
End Sub

Related

How to access Form.Textbox.Text property when the source query returns no results?

I am making a continuous form for searching that self-updates as the user types in multiple search boxes.
The code works up until the user types in parameters that don't correspond to any records.
The query then can't find anything and I get the error
"Can't use the property or method when the control doesn't have the focus"
I could not figure out what element of the form is doing it. Adding the .SetFocus to the textbox control didn't help.
Any ideas on how to either
Set focus to the textbox again and prevent it from being lost, or
Figure out what is stealing the focus and disable it?
The following sub is called in the textbox_Change sub. I added a workaround.:
Private Sub RefreshTB(textbox As Control)
'This is to prevent Acces from removing trailing spaces
'If the textbox isn't empty and there is a space at the end, don't requery. This preserves trailing spaces as Access trims them on Me.requery
If Len(textbox.Text) <> 0 And InStr(Len(textbox.Text), textbox.Text, " ", vbTextCompare) Then
Exit Sub
End If
'If the last character isn't a space, requery on change to show new results of the query
Me.Requery
'The workaround: If the query returns no results, detect that, warn the user and clear search box. Requery to show some results again.
If DCount("*", "DatasetsFilterQ") = 0 Then
If MsgBox("No results found. The last TextBox you searched in will be cleared.", vbOKOnly, "No Records") = vbOK Then
textbox = ""
Me.Requery
End If
Exit Sub
End If
textbox.SetFocus
textbox.SelStart = Len(Nz(textbox.Text))
End Sub
I tried a filter but ran into the same error when passing .text value to the function.
You can't set SelStart to Null, so avoid that with Nz:
textbox.SelStart = Len(Nz(textbox.Value))

Error catching a form in Access using VBA

So i have a form that's updating a table in Microsoft Access. I'm using a BeforeUpdate event call to stop the form from updating if the 'first name' hasn't been filled in.
I basically only want the form to be saved once everything has been filled in, and then switch to see the updated table (the bit under If not cancel).
Currently the popup box to say 'You must enter a First Name' correctly fires, the next pop up box asking if the user wants to undo any changes fires. But then a pop up box saying 'No current record' appears and then the view changes to the table. I'm not sure why this is all happening.
Option Compare Database
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = False
' perform data validation
If IsNull(Me.customer_f_name) Then
MsgBox "You must enter a First Name.", vbCritical, "Data entry error..."
Me.customer_f_name.BorderColor = vbRed
DoCmd.GoToControl "customer_f_name"
Cancel = True
End If
If Not Cancel Then
DoCmd.SelectObject acTable, "ticket_tracker_table"
DoCmd.Requery
DoCmd.GoToRecord acDataTable, "ticket_tracker_table", acLast
End If
' if the save has been canceled or did not pass the validation , then ask to Undo changes
If Cancel Then
If MsgBox("Do you want to undo any changes?", vbYesNo, "Confirm") = vbYes Then
Me.Undo
End If
End If
End Sub
Review https://learn.microsoft.com/en-us/office/vba/api/Access.Form.BeforeUpdate(even)
Instead of GoToControl, use SetFocus.
I did a very simple test with the Undo question and it does work:
Private Sub Form_BeforeUpdate(Cancel As Integer)
If IsNull(Me.customer_f_name) Then
MsgBox "Must enter customer name."
Cancel = True
If MsgBox("Do you want to undo edits?", vbYesNo) = vbYes Then Me.Undo
Me.customer_f_name.SetFocus
End If
End Sub
Suggest you put table code in AfterUpdate event.
so to supplement J7, with some big picture view: "basically only want the form to be saved once everything has been filled in" …. that is swimming against the tide; which is why you are having to write a lot of code. The product enters data as you go fundamentally. that is it's core design.
it is very normal to do field checks as you go - typically in the AfterUpdate event, the check code is applied and if invalid - generate a message box and invoke an Undo plus reset the focus back to the field they were attempting to leave.
A totally different design, in some cases it may justify a temp local duplicate table just for the purposes of holding form input data - - this approach allows a very elaborate check(s) against data in the production database; where upon if valid an Append Query then writes the data into the permanent table.

Validating textbox entry on Userform (Excel VBA)

I have a textbox (in this instance it is textbox11) where the front end user will need to input "Half Day" in some form or another.
Here is my code:
Private Sub TextBox11_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Me.TextBox11 = "half" Or Me.TextBox11 = "half day" Or Me.TextBox11 = "half-day" Or Me.TextBox11 = 0.5 Or Me.TextBox11 = "1/2" Then
Me.TextBox11 = "Half Day"
End If
End Sub
When I run it, it works wonderfully - for the conditions I have set. However, if a user, say, inputs "hALf dAy", then this will not be validated and fixed to standard form as it is not on my condition list.
There is noway where I could put all permutations of what a user might put in. Is there a way to make this case-insensitive? So no matter what case a user puts in, it will check against my conditions anyway.
Thanks
LCase (or UCase) the user input. By converting all characters to lower case, and then comparing to your lower-case strings, you are effectively case-insensitive. Here's an example of that.
Private Sub TextBox11_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Select Case Trim(LCase(Me.TextBox11.Text))
Case "half", "half day", "half-day", "0.5", ".5", "1/2"
Me.TextBox11.Text = "Half Day"
Case Else
' do nothing?
'
'
End Select
But if you really want validation the best option is to use a ComboBox with predefined values rather than a text box where the user can type any ol' garbage.

My VBA code is not reacting when a condition has been met

I am using VBA in Microsoft Access. I want the code to run before the user completes each entry of "downtime". I am trying to make sure that the value of a box is not a negative number. The box actually holds a formula. I don't know if that matters but, I thought I would mention that. I want to check the result of the calculation (the value that is showing in that box) and if it is less than 0, I want a MsgBox to pop up. My code is doing nothing. No error, no pop-up, no warnings.
Here is my code.
Private Sub Form_BeforeUpdate(Cancel As Integer)
If (Me.RunningTotal.Value < 0) Then
MsgBox (RunningTotal & "Please check your downtime.")
Cancel = True
End If
End Sub
I have tried using the "RunningTotal" in brackets as well with no luck. I have also tried beforeupdat as well as afterupdate.
I got it to work. I had to put the code in the user's data entry box AND as an "after update" since the calculation wouldn't happen until after the entry has been made. Thank you, Darren, for your help. :) Here is the code that works.
*Private Sub MinutesDown_AfterUpdate()
If (Me.RunningTotal < 0) Then
MsgBox (RunningTotal & "Please check your downtime.")
Cancel = True
End If
End Sub*

MS Word Document Form - Check Value of Text Form Field on Exit

I'm creating a Form in Microsoft Word. I have several 'Text form fields' some of which I want to restrict so users can only enter numbers. I don't understand why Microsoft gives you the option to change the 'Type' to 'Number' when that still allows any value to be input. Since that seems to be the case I have turned to VBA.
I'm trying to run a macro when the user exits one of these fields, to make sure the input is valid. I would rather not create a new macro for each field I want to restrict to numeric.
I think my problem is that I don't know how to get the result of the current field. I could create a different macro for each field, and get the result by specifying its name explicitly, but it seems like a smarter way would exist.
Here's what I have so far.
Sub validateNumericFields()
'Check to see if the value in the current field is numeric
'If it is not, send a message to the user, and set value to default value
If IsNumeric(Selection.Fields(1).Result) = False Then
MsgBox "You must enter a valid number.", vbExclamation
Selection.Fields(1).Result = Selection.Fields(1).TextInput.Default
End If
End Sub
There are various ways to get the "name" of a form field, since this is also a bookmark. The FormField object does have a Name property, but I can't get to it from the Selection object available when OnExit runs. But I can get the bookmark name, so:
Sub validateNumericFields()
'Check to see if the value in the current field is numeric
'If it is not, send a message to the user, and set value to default value
Dim ff As word.FormField
Set ff = ActiveDocument.FormFields(Selection.Bookmarks(1).Name)
If IsNumeric(ff.Result) = False Then
MsgBox "You must enter a valid number.", vbExclamation
ff.Result = ff.TextInput.Default
End If
End Sub