VBA UserForm TextBox Only Allow Numbers and Empty Text - vba

In my userform I want to MsgBox if TextBox not contain Numbers or empty.
This is my code but in another case when the TextBox = "" Empty the MsgBox appear to me, so the issue with me is the empty TextBox.
Private Sub TB1_Change()
If TypeName(Me.TB1) = "TextBox" Then
With Me.ActiveControl
L12.Caption = Val(TB1.Text) * Val(TB2.Text)
If Not IsNumeric(.Value) And .Value <> vbNullString Then
MsgBox "Sorry, only numbers allowed"
.Value = vbNullString
End If
End With
End If
End Sub

Use the Key Press event for this purpose.
Private Sub TB1_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If Not IsNumeric(Chr(KeyAscii)) Then KeyAscii = 0
End Sub
This procedure will just ignore anything you enter if it isn't a number, but you can modify both the condition and the output. For example, you might allow a decimal point to be entered, or you might wish to show a message box - perhaps only on the second try.

You may use the AfterUpdate event handler instead of the Change event, might also want to use the Exit event and cancel the exit if the user enters an invalid value:
Option Explicit
Private Sub TB1_AfterUpdate()
'Check whether the value is numeric or empty:
If Not IsValNumeric(Me.TB1.Value) Then
MsgBox "Sorry, only numbers allowed"
Me.TB1.Value = vbNullString
Else:
'Do something...
MsgBox val(TB1.Text) * val(TB2.Text)
End If
End Sub
Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
'Prevents the user from EXIT the TextBox if value is not numeric/empty
Cancel = Not IsNumeric(Me.TB1.Value)
End Sub
Private Function IsValNumeric(val$) As Boolean
Dim ret As Boolean
'check for numeric value only and allow empty value as a zero value
ret = IsNumeric(val) Or Len(val) = 0
IsValNumeric = ret
End Function

You can wait until the user finishes their input and then test the field.
For usability, the message box should be replaced with a caption and an icon/picture like this "A number must be entered here."
These would be displayed next to the text box when the input is incorrect. Then hidden when the input is corrected. The submission of the form can be blocked until all the errors have been corrected.
This allows the user to enter the request data and then fix any input errors. This is better than stopping them every time they make a mistake.
The event is changed from Change to Exit.
Private Sub TB1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TypeName(Me.TB1) = "TextBox" Then
With Me.ActiveControl
L12.Caption = Val(TB1.Text) * Val(TB2.Text)
If Not IsNumeric(.Value) Or .Value = vbNullString Then
MsgBox "Sorry, only numbers allowed"
.Value = vbNullString
End If
End With
End If
End Sub
The vbNullString test has also been updated.

Since you are trying to allow only "Numeric" and "Blank" then the code below would deliver your needs.
Private Sub TB1_Change()
if IsNumeric(Me.TB1.Value) = True or Me.TB1.Value = vbNullString then
'Good data, nothing to MSG
Else
MsgBox "Your input data is not valid"
Endif
End Sub

Related

Userform - Redirect focus on textbox after MsgBox

I hope this is not that stupid, but I really did not find a post that was working for me.
Situation: I want someone to put a date into a textbox in a Userform.
ErrorHandler: I wanted to have a very simple solution if the user doesn't enter the right format. (EB_Start.Activate and EB_Start.SetFocus are NOT working at all)
For this I got:
Private Sub EB_Ende_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo Error_Handler
Me.EB_Ende = CDate(Me.EB_Ende)
Error_Handler:
EB_Start.Activate
EB_Start.SetFocus
MsgBox ("Please enter a valid date"), , "Datum"
End Sub
Problem:
My Question is now, how do I redirect the focus on the textbox(EB_Ende)
The current reaction is, after the user presses Enter after the MsgBox showed up, It continued to the next textbox, but I want the user to be forced to reenter a valid date in the textbox.
If someone could help me out with this, or redirect me to a Post or link that will answer my question I would really appreciate it.
Best regards,
Lutscha
This is the whole UserForm
There are a couple of issues with your code (e.g. not exiting before the error handler, and do you want to use Cancel=msoTrue to cancel the text entry to EB_Ende when you get an error?) so you could try this:
Private Sub EB_Ende_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo Error_Handler
Me.EB_Ende = CDate(Me.EB_Ende)
Exit Sub
Error_Handler:
EB_Start.SetFocus
MsgBox ("Please enter a valid date"), , "Datum"
End Sub
Or, you could skip the error-hander entirely:
Private Sub EB_Ende_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If IsDate(Me.EB_Ende) Then
Me.EB_Ende = CDate(Me.EB_Ende)
Else
Cancel = msoTrue
EB_Start.SetFocus
MsgBox ("Please enter a valid date"), , "Datum"
End If
End Sub
Setting focus in BeforeUpdate event won't work - it is too soon. It is fired before focus is moved to the next control. Better approach is to handle Exit event and cancel it when needed:
Private Sub EB_Ende_Exit(ByVal Cancel As MSForms.ReturnBoolean)
On Error GoTo Error_Handler
EB_Ende = CDate(EB_Ende)
Exit Sub '<-- exit sub when there is no error
Error_Handler:
Cancel = True
MsgBox ("Please enter a valid date"), , "Datum"
End Sub
The funny thing is, you used the answer as a tag on your question:
Me.EB_Ende.SetFocus
Here is more information on SetFocus.
Something else that might help... you can change the default order that objects are "tabbed" through. (ie., what cell should get focus after you press enter or tab in the current control:
worked perfect
Private Sub txtSalary_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
If Not IsNumeric(txtSalary) Then
MsgBox "Please, only numbers!", vbRetryCancel
Cancel = True
txtSalary = ""
End If
If IsNumeric(txtSalary) Then
txtSalary = Format(txtSalary, "$#,##0.00")
End If
End Sub

Runtime Error 1004 - BeforePrint - Avoid printing if cells are empty

I am trying to create a macro to prevent users from printing a form if they don't fill out all cells. However, I am getting an error message:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
If Application.Sheets("Form").Range("B4,C4,D4,E4,F4,G4,H4,I4,J4,K4,L4,M4,B5,C5,D5,E5,F5,G5,H5,I5,J5,K5,L5,M5,B6,C6,D6,E6,F6,G6,H6,I6,J6,K6,L6,M6,B7,C7,D7,E7,F7,G7,H7,I7,J7,K7,L7,M7,B8,C8,D8,E8,F8,G8,H8,I8,B9,C9,D9,E9,F9,G9,H9,I9,B11,C11,D11,E11,F11,G11,H11,I11,B12,C12,D12,E12,F12,G12,H12,I12,B13,C13,D13,E13,F13,G13,H13,I13,B14,C14,D14,E14,F14,G14,H14,I14,B16,C16,D16,E16,F16,G16,H16,I16,B17,C17,D17,E17,F17,G17,H17,I17").Value = "" Then
Cancel = True
MsgBox "Fill out all the cells"
End If
End Sub
I have another macro for another form that has fewer cells and that one works just fine:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
If Application.Sheets("Form 2").Range("C4,C5,C6,D4,D5,D6,F4,F5,F6,B8,B9,B10,B11,C8,C9,C10,C11,D8,D9,D10,D11,E8,E9,E10,E11,C13,D13,C16,C17,C18,F16,F17,F18,C22,D22").Value = "" Then
Cancel = True
MsgBox "Fill out all the cells"
End If
End Sub
What can I do to solve this problem?
It seems that there is a limit to line length or to how long of a string you can put into a range(). But you can consolidate it like this. Also I think that the return value from a range() with more than one cell is an array so I am not sure if it is valid to compare it to a string like you did.
Try this:
Private Sub Workbook_BeforePrint(Cancel As Boolean)
For Each cell In Application.Sheets("Form").Range("B4:M7,B8:I9,B11:I14,B16:I17")
If cell.Value = "" Then
Cancel = True
MsgBox "Fill out all the cells"
Exit Sub
End If
Next
End Sub

Excel userform - setting focus of textbox on exit if condition not met

I have an Excel userform with textboxes to put various information (first name, last name, gender, height, etc.). For some of the textboxes, I want to apply a sort of validation.
For the gender field, for example, the only values that are acceptable are "M" or "F." I have this bit of code. If you type "M" or "F" and tab out of the field, it goes to the next textbox. But if it's anything else, the MsgBox will pop up like it should, but after you click OK, the focus is not set to the textbox.
What am I doing wrong? Shouldn't this work?
Private Sub txtGender_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If txtGender.Value <> "M" And txtGender.Value <> "F" Then
MsgBox ("Invalid gender.")
txtGender.SetFocus
End If
End Sub
You can cancel the Exit event within your If statement.
Private Sub txtGender_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If txtGender.Value <> "M" And txtGender.Value <> "F" Then
MsgBox ("Invalid gender.")
Cancel = True
End If
End Sub

Access Required Fields Before Exiting Form

I have this BeforeUpdate code to check if certain fields are filled out. These fields are required and must be filled or the record shouldn't save. If other fields have been filled without the ID and Staff field, then the message box prompts pop up (These are required fields, etc.).
Private Sub Form_BeforeUpdate(Cancel As Integer)
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
Cancel = True
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Cancel = True
Me.[Staff].SetFocus
End Sub
I have a 'Close Form' button as follows:
Private Sub CmdCloseForm_Click()
DoCmd.Close , ""
End Sub
When this button is clicked, I get the warning that the fields aren't filled, but then the form closes. I want a Yes/No message box asking the user to see if they would still like to close the form or not. I've made a Yes/No messagebox in the BeforeUpdate sub. However it doesn't stop the sub CmdCloseForm.
Is there a way to create a messagebox to confirm if the user wants to exit the form?
For example:
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then
Exit Sub
End If
If I put the above Msgbox into the CmdCloseForm function, it prompts the user before letting them know that they're missing the ID/Staff fields.
I came about this solution by Mr. Craig Dolphin and it worked for me.
The way he approached is to have a generic validation function that is saved in a general purpose module (ie not in a form module).
Public Function validateform(myform As Form) As Boolean
'returns true if all required fields have data, or false if not.
'It will also create a popup message explaining which fields need data
Dim boolresponse As Boolean
Dim strError As Variant
Dim ctl As Control
boolresponse = True
strError = Null
With myform
For Each ctl In .Controls
With ctl
If .Tag = "required" Then
If .Value & "" = "" Then
boolresponse = False
strError = (strError + ", ") & .Name
End If
End If
End With
Next ctl
End With
If strError & "" <> "" Then MsgBox "The following information must be entered first: "
& strError, vbInformation
validateform = boolresponse
End Function
Then, for any fields that are absolutely required, you just set the Tag property of the control to 'required'
You can then, for example, call the function from the onclick event of the 'save' button or 'close' button.
Private Sub Command5_Click()
On Error GoTo Err_Command5_Click
If Me.PrimaryID & "" <> "" Then
If validateform(Me) Then DoCmd.Close
Else
DoCmd.Close
End If
Exit_Command5_Click:
Exit Sub
Err_Command5_Click:
MsgBox Err.Description
Resume Exit_Command5_Click
End Sub
this essentially checks to see if the auto pk field has a value indicating that the record has been created. If it has, then it validates the required fields. If not, it closes without checking. If the record has been created, it validates the form and only closes if all the required fields are filled in. If more data is required, then it pops up a message reminding the user which fields to fill in.
The nice part of this is that you can set conditional requirements using the vba to set the tag property of certain controls to required if another field is updated to a value that you want to trigger an additional requirement. Of course, if you do that then you also need to initialize those tag value in the on_current event for when you switch records.
Many thanks to Mr. Craig Dolphin
Since you want to show consecutive pop-ups, cancel the auto-update altogether and validate on Close.
If validation is successful save the record, if not notify the user.
Private Sub Form_BeforeUpdate(Cancel As Integer)
Cancel = True 'cancel auto-update
End Sub
'Validate and either Save or Close
Private Sub CmdCloseForm_Click()
If Me.Dirty Then
If IsFormValidated Then
DoCmd.RunCommand acCmdSaveRecord
Else
If MsgBox("Would you like to close the form still? Changes won't be saved.", vbYesNo + vbQuestion, "Warning") = vbNo Then Exit Sub
End If
End If
DoCmd.Close acForm, Me.Name, acSavePrompt
End Sub
'Validation
Private Function IsFormValidated() As Boolean
IsFormValidated = True 'assume all is in order
If Nz([ID], "") = "" Then
MsgBox "The ID field is required.", vbExclamation, "Required Field"
IsFormValidated = False
End If
If Nz([Staff], "") = "" Then
MsgBox "Staff field is required.", vbExclamation, "Required Field"
Me.[Staff].SetFocus
IsFormValidated = False
End If
End Function

Excel VBA ComboBox1_DropButtonClick Event

I got macro below which fires twice (showing same MessageBox twice). First when ComboBox1 opens and second when ComboBox1 closes.
Private Sub ComboBox1_DropButtonClick()
If Me.ComboBox2.Text = "" Then
MsgBox "Fill text box"
Else
'Do stuff
End If
End Sub
Is there any way to make it show MessageBox once. I want user to select the value in ComboBox1 first before clicking on ComboBox2 DropButton.
Here is a very unelegant work-around using a "count" variable that prompts the MsgBox only the first and not the second time.
Dim count As Integer
Private Sub ComboBox1_DropButtonClick()
count = count + 1
If Me.ComboBox2.Text = "" Then
If count = 1 Then
MsgBox "Fill text box"
Else
count = 0
End If
Else
'Do stuff
End If
End Sub
However, I highly suggest to use the ComboBox1_Change() event if it's not necessary to use the drop button one.
P.S.: the declaration of the "count" variable needs to stay out of the method. This is due to the fact that:
if it stays inside, it's a local variable of the method and so loses its modifications every time the method is ended;
if it stays outside, it will keep the modifications even once the method has ended its run.
I would do it using the combobox_enter event, but this only checks when the focus is switched
Private Sub ComboBox1_Change()
If ComboBox1.Text = "" Then
ComboBox2.ShowDropButtonWhen = fmShowDropButtonWhenNever
Else
ComboBox2.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End If
End Sub
Private Sub ComboBox2_Enter()
If ComboBox1.Text = "" Then
MsgBox "Must first set value to combobox1"
ComboBox1.SetFocus
End If
End Sub
Private Sub UserForm_Initialize()
ComboBox1.AddItem "None", 0
ComboBox1.AddItem "Select Me", 1
ComboBox2.AddItem "None", 0
ComboBox2.AddItem "Select Me", 1
ComboBox2.ShowDropButtonWhen = fmShowDropButtonWhenNever
End Sub
My code does some extra things that I just think look pretty, you really only need the _Enter function