问题
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
回答1:
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.
回答2:
For your code you could use UCase
Private Sub TextBox11_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
dim inp as string
inp = ucase(Me.TextBox11.text)
If inp = "HALF" Or inp = "HALF DAY" Or inp = "HALF-DAY" Or Me.TextBox11 = 0.5 Or Me.TextBox11 = "1/2" Then
Me.TextBox11 = "Half Day"
End If
End Sub
来源:https://stackoverflow.com/questions/51010634/validating-textbox-entry-on-userform-excel-vba