Ensure user inputs text in INPUT Box in CAPS - excel

I have a input box that the user needs to put in some specific text. The text must be in uppercase. But when i run the code and insert the text in lower case, it still runs.
HERE:
KnownError = InputBox(PayRatesTable.ListColumns("Name").DataBodyRange(i) & " is showing "
& PayRatesTable.ListColumns("Hourly or Salary").DataBodyRange(i) & " for role " &
PayRatesTable.ListColumns("All Roles").DataBodyRange(i) & ". Please type KNOWN ERROR (All
CAPS) to
continue.")
If StrPtr(KnownError) = 0 Then
MsgBox "Process Aborted"
Exit Sub
End If
If KnownError <> "KNOWN ERROR" Then
MsgBox "Please type KNOWN ERROR (All CAPS) to continue or cancel to stop the
proccess"
GoTo HERE
End If
Any ideas on how to force the use of uppercase??

Related

Compare part of Combobox1.value with combobox2

I have created a userform with comboboxes, I would like to compare the a part of combobox 2 with the value of combobox 1. if they do not match there should be an error given (as in my code, see below), the code that I made is not working, but I do not know what is wrong.
the error that is showing is:
Compile error: Sub or Function not defined #Find
If Left(Me.ComboBox2.Value(Find(" -", Me.ComboBox2.Value, 1) - 1)) <> Me.ComboBox1 Then
MsgBox "The tag of " & m2.ComboBox2.Tag & "does not match with selected BIN"
Exit Sub
End If
It is working already with the following code, thanks anyway for the help.
If Left(Me.ComboBox2.Value, InStr(Me.ComboBox2.Value, " -") - 1) <> Me.ComboBox1 Then
MsgBox "The tag of " & me.ComboBox2.Tag & "does not match with selected BIN"
Exit Sub
End If

Excel VBA Textbox_Exit Event Handler

At a road block here. Simple user form using three text boxes, one for user id, two to enter serial number using hand scanner. User loads excel file, userform.show loads, user enters id then simple validation to verify numberic number, then focus set on first textbox, user scans barcode to input serial number, again simple validation to ensure numeric and length, same with last textbox, scan serial number, validate first textbox entry matches second textbox entry.
Hand scanner is used to input serial number and also returns a "return carriage" character; e.g. enter button press after serial number scan.
Using "return carriage" to fire textbox_exit event handler. Issue is very intermittent but consistent. I load userform, input data, when record is complete, data is transferred to object worksheet. However, when troubleshooting, I initially open workbook and userform, create a few records, save, and close. Everything works well and data is recorded and archived. Issue generally arises when i load workbook a second time, enter data for one record, save, and begin second record. Once serial number is entered into first textbox, exit event never fires using "return carriage". I can manually transfer focus to other objects; e.g. diff textbox, but the overall operation is not as expected.
I have tried inserting application.eventhandler=true commands, different event handlers, as well as numerous code changes; e.g. exit sub at end of IF statements, to make this work.
Thought I would reach out to the community for some feedback. FYI, issues still arises if I simulate hand scanner using copy/paste and enter key.
Example of exit event handler for first serial textbox below.
Private Sub SerialIn_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Cancel = False
If Not IsNumeric(SerialIn.Value) Then 'validate serial number is numeric
'error msg serial number is not numeric
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
MsgBox Msg, vbCritical, "Warning" 'display msg
Cancel = True 'stop user from changing focus
SerialIn.SelStart = 0 'highlight user text
SerialIn.SelLength = Len(SerialIn.Value) 'select user text
'Image1.Picture = LoadPicture(StopLightRed) 'display red stop light
Exit Sub
Else
If Not Len(SerialIn.Value) = 19 Then 'validate serial number length
'error msg incorrect length
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
MsgBox Msg, vbCritical, "Warning"
Cancel = True 'stop user from changing focus
SerialIn.SelStart = 0 'highlight user text
SerialIn.SelLength = Len(SerialIn.Value) 'select user text
'Image1.Picture = LoadPicture(StopLightRed) 'display red stop light
Exit Sub
Else
SerialInTime.Caption = Now 'record date and time
'Image1.Picture = LoadPicture(StopLightYellow) 'display yellow WIP stop light
Me.SerialOut.SetFocus
Exit Sub
End If
End If
End Sub
New code:
Private Sub SerialIn_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Cancel = ValidateSerialIn(SerialIn)
End Sub
Function ValidateSerialIn(ByVal TextBox As Object) As Boolean
If Not IsNumeric(SerialIn.Value) Then 'validate serial number is numeric
'error msg serial number is not numeric
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
msgbox Msg, vbCritical, "Warning" 'display msg
SerialIn.SetFocus
SerialIn.SelStart = 0 'highlight user text
SerialIn.SelLength = Len(SerialIn.Value) 'select user text
'Image1.Picture = LoadPicture(StopLightRed) 'display red stop light
ValidateSerialIn = True
Else
If Not Len(SerialIn.Value) = 19 Then 'validate serial number length
'error msg incorrect length
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
msgbox Msg, vbCritical, "Warning"
'Cancel = True 'stop user from changing focus
SerialIn.SelStart = 0 'highlight user text
SerialIn.SelLength = Len(SerialIn.Value) 'select user text
'Image1.Picture = LoadPicture(StopLightRed) 'display red stop light
ValidateSerialIn = True
Else
SerialInTime.Caption = Now 'record date and time
'Image1.Picture = LoadPicture(StopLightYellow) 'display yellow WIP stop light
ValidateSerialIn = False
End If
End If
End Function
Third go using Tim's TextBox_Change solution:
Private Sub SerialIn_Change()
Dim v
v = ScannedValue1(SerialIn.Text)
If Len(v) > 0 Then
If Not IsNumeric(v) Then 'validate serial number is numeric
'error msg serial number is not numeric
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
msgbox Msg, vbCritical, "Warning" 'display msg
SerialIn.Text = vbNullString
Else
If Not Len(v) = 19 Then 'validate serial number length
'error msg incorrect length
Msg = "Opps, something went wrong! Serial number was incorrect." _
& vbNewLine & vbNewLine & "Rescan module serial number."
msgbox Msg, vbCritical, "Warning"
SerialIn.Text = vbNullString
'Image1.Picture = LoadPicture(StopLightRed) 'display red stop light
Else
SerialInTime.Caption = Now 'record date and time
'Image1.Picture = LoadPicture(StopLightYellow) 'display yellow WIP stop light
SerialOut.SetFocus
End If
End If
End If
End Sub
'check if a value ends with vbcrlf or vblf
' - if yes strip that off and return the rest
' - otherwise returns empty string
Function ScannedValue1(vIn) As String
Dim rv As String
If Right(vIn, 2) = vbCrLf Then
ScannedValue1 = Replace(vIn, vbCrLf, "")
ElseIf Right(vIn, 1) = vbLf Then
ScannedValue1 = Replace(vIn, vbLf, "")
End If
End Function
If you want to detect the "Enter" from the scanner then use the Change event to check if the textbox value ends with vbCrLf or vbLf (in that order): if it does, then trigger the "scan" action.
Note you need to set your textbox to "multiline=true" and "EnterKeyBehaviour = true" in order for the Change event to capture the enter key.
Private Sub TextBox1_Change()
Dim v
v = ScannedValue(TextBox1.Text)
If Len(v) > 0 Then
TriggerScanAction v
TextBox1.Value = ""
End If
End Sub
'check if a value ends with vbcrlf or vblf
' - if yes strip that off and return the rest
' - otherwise returns empty string
Function ScannedValue(vIn) As String
Dim rv As String
If Right(vIn, 2) = vbCrLf Then
ScannedValue = Replace(vIn, vbCrLf, "")
ElseIf Right(vIn, 1) = vbLf Then
ScannedValue = Replace(vIn, vbLf, "")
End If
End Function
'execute some action triggered by a scanned value
Sub TriggerScanAction(v)
MsgBox "You scanned " & v
End Sub
The Exit event has more to it than meets the eye. On most forms, one enters a value in a textbox and then clicks "OK", a command button. Tbx.Exit event occurs. It also occurs if you click anywhere else, such as a button to close the form. In your system the CR triggers the event as well, and that would appear to be the problem.
When a CR or TAB is entered in your Tbx the form's tapping sequence takes over. The exit occurs, followed by the enter event of the next control in your tapping order. (Compare that to the manual change of focus that occurs when the user determines the next control.)
So, the solution should be not to use the Exit event but to let the CR initiate a change of focus, using the tapping order setting, which lands the focus on an "OK" button, then let that button's Enter event trigger its Click event (if it doesn't do that by default).
You probably want a cycle there, where the CR triggers the worksheet entry and the focus comes back to the Tbx. That's one more reason not to use the Exit event because you don't want an entry made in the worksheet when you exit the Tbx to close the form.
However, perhaps your form doesn't have or need an "OK" button. In that case I would recommend the BeforeUpdate event of the Tbx. Both Exit and BeforeUpdate occur in close succession. The sequence isn't important however (though that's not the reason why I forgot it :-)) but their nature. Use the exit event in the context of form control, setting focus or reacting to focus change. BeforeUpdate obviously refers to data. Each of these events is fine tuned to its own task and therefore does it better than the other.

Display Error message when connection or Invalid Username or Password in VBA

I have tried below code but i want to use MsgBox to display the error message (-2147217843)
Else
'Display errors..
For Each Err In objConn.Errors
Debug.Print Err.Description
Next
End If
Just use MsgBox function with vbCritical style.
Dim Msg, Style, Title
Style = vbOKOnly + vbCritical ' Define buttons.
Title = "Error" ' Define title.
Msg = "The following errors have been occurred:" ' Prepare message template.
' Build message.
For Each Err In objConn.Errors
Msg = Msg & vbNewLine & Chr(149) & " " & Err.Description
Next
Call MsgBox(Msg, Style, Title) ' Display error message
You could also use vbCrLf instead of vbNewLine new line character.
This is one google search away.
Msgbox(Err.Description)
Not sure how I can further enrich the answer with the current state of the question.

error message not appearing though there is no error and put exit sub before error hadeler statment in vba

I have been figuring out how to pop up msg box if there is error. I have below code but this code does not jump to error handler if there is error and Exit the sub.
Sub Validate_Region()
Dim str_DEPARTMENT_NAME As String
On Error GoTo Reion_Error
If Left(Range("M4"), 2) = "As" Then
str_DEPARTMENT_NAME = "India"
ElseIf Left(Range("M4"), 2) = "ME" Then
str_DEPARTMENT_NAME = "Middle East"
End If
'Get value of region selected in Master File
str_regionvalue = Workbooks("Master Report").Sheets("Home").Range("T8")
If str_regionvalue = str_DEPARTMENT_NAME Then
MsgBox ("You have selected " & str_regionvalue & " region"), vbInformation
End If
Exit Sub
Reion_Error:
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
ActiveWorkbook.Close
End Sub
I just copy/pasted your code and it works well for me:
I don't know from where this sub is called and what type of variable is used on str_regionvalue (seems like Variant)
So what can you do with this:
Get rid of Exit Sub on line #19.
Put Err.Number check in your error handler:
Reion_Error:
If Err.Number <> 0 Then
MsgBox ("Please select the correct Region.") & vbNewLine & vbNewLine & ("You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region"), vbCritical
'by the way, you can try to set ActiveWorkbook.Saved to True, to get rid from pop-ups on Close
ActiveWorkbook.Close
End If
Try to look for error number thru debugging (debug.print err.number or place some stop's to do this manually). Or add err.number to Watches and check Break when value changes so you can track where error raised and cleared (if raised).
Err object
P.S. You got some ridiculous MsgBoxes, if you really like parentheses, use them like this:
Call MsgBox("Please select the correct Region." & vbNewLine & vbNewLine & _
"You have selected " & str_regionvalue & " region" & " In Home Sheet of Master Report and pulled the data for " & str_DEPARTMENT_NAME & " region", vbCritical)
Under Tools >> Options in the VB Editor: on the General tab make sure you don't have "Error trapping" set to "Break on all errors"
Check your syntax, you have quite a few unnecessary brackets and commas in your msgbox statements. Try something like:
returnval = MsgBox ("Put message here" , vbInformation)
OR
MsgBox "another message " & vbnewline & "some more message", vbcritical
The code looks fine and compiles now but I think your error may be elsewhere. Possibly in:
str_regionvalue = Workbooks("Master report").Sheets("Home").Range("T8")
I'd suggest:
Leave the 'exit sub' in. It's correct.
Add 'Option Explicit' to the top of the code - it will force you to declare all variables (str_regionvalue isn't declared)
Set your Under Tools >> Options in the VB Editor: to 'Break on Unhandled Errors'.
Put in a breakpoint (Debug >> Add Watch) at the top of the code and run through it step by step using Debug >> Step Into.

If Err.Description = "...." Then ..... in VBscript

I'm fixing the bellow error "datatable importsheet operation failed. Invalid file" using this way:
On error resume next
DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2"
If Err.Description = "The DataTable.ImportSheet operation failed. Invalid file." \n "Line (20): "DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2""." Then
list of instructions
end if
But I got this error:
The test run cannot continue due to a syntax error.
Expected 'Then'
Line (24): "If Err.Description = "The DataTable.ImportSheet operation failed. Invalid file." \n "Line (20): "DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2""." Then".
Everything looks right. Please any help ? where I'm wrong ?
I'm really struggling with what you are trying to do and your comments are not helping...
When using
On Error Resume Next
and you encounter an error while executing a statement the following things will happen;
The statement will be skipped and the script will move to the next statement and carry on execution.
The object Err will be populated with details of the error that caused the statement to be skipped.
The Err object is made up of a few key properties that describe the error that occurred;
Number - The Error Code of the error that was raised.
Source - The Source of the error that was raised, this can be 3rd party library, the VBScript Runtime etc.
Description - A free text description of the error.
If you want to check for error
The DataTable.ImportSheet operation failed. Invalid file.
when
DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2"
is executed you need to capture the Err.Number code that corresponds to that specific error.
Something like this;
On Error Resume Next
DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2"
'Check that an error occurs
If Err.Number <> 0 Then
'Identify specific error and deal with accordingly.
Select Case Err.Number
Case 20012 'Code for DataTable.ImportSheet operation failed
'List of instructions...
Case Else
'Unhandled error show to screen
MsgBox "Error: " & Err.Number & " (" & Err.Source & ") - " & Err.Description
End Select
'Finished handling the error
Call Err.Clear()
End If
What I find most confusing is the miss-information in this thread.
"I need the description and not the number and the problem is to use Err.Details and not Err.Description in my case. Now, it is working." - Ref
The Err object does not contain a property called Details unless this is something specific to QTP but so far I haven't been able to find anything with a quick Google Search. So how you can say "it is now working" is beyond me.
Basic rules:
Double Quotes (") are escaped by doubling ("")
No escapes like "\n" in VBScript string literals (concatenation (or replacement) needed)
The concatenation operator is &
Basic strategy: Simplify, Divide, and conquer:
>> s = "1" & vbCrLf & "-""pi""-"
>> t = "1" & vbCrLf & "-""pi""-"
>> WScript.Echo s
>> WScript.Echo t
>> If s = t Then
>> WScript.Echo "no surprise"
>> End If
>>
1
-"pi"-
1
-"pi"-
no surprise
>>
Added:
Applied to your string/error message:
's = "The DataTable.ImportSheet operation failed. Invalid file." \n "Line (20): "DataTable.ImportSheet Environment("STPFilePath"),Environment("TestScriptName"),"Action2""."
s = "1" & vbCrLf & "2: ""3(""4""),5(""6""),""7""."
WScript.Echo s
output:
cscript 39878005.vbs
1
2: "3("4"),5("6"),"7".
You are getting a syntax error because the double quotes in your if statement are not escaped.
I'm not sure what you are trying to do here and maybe using Err.Number makes more sense but if you want to avoid the syntax error then use this code:
If Err.Description = "The DataTable.ImportSheet operation failed. Invalid file."" \n ""Line (20): ""DataTable.ImportSheet Environment(""STPFilePath""),Environment(""TestScriptName""),""Action2""." Then
''' list of instructions
End If
Also, you cannot use \n if you want to compare 2 lines in if statement. Use CHR(13) or CHR(10) instead of \n. I.e.
If Err.Description = "The DataTable.ImportSheet operation failed. Invalid file."& CHR(13) &"Line (20): ""DataTable.ImportSheet Environment(""STPFilePath""),Environment(""TestScriptName""),""Action2""." Then
'''list of instructions
End If
Again: Using Err.Number will make more sense as any extra/missing space/newline in above If condition will fail the condition.
Try to Replace the Err.Description line with this
If Err.Description = "The DataTable.ImportSheet operation failed. Invalid file." & vbCrLf & "Line (20): DataTable.ImportSheet Environment(" & STPFilePath & "),Environment(" & TestScriptName & ")," & Action2 & "." Then
Good Luck.!

Resources