Validate entry of an input box - validation

Im trying to get an input box to validate the entries a user will make.
i'm using the below script but cant get the validation to work, any help would be appreciated.
Sub inputbox()
Dim Manager As Long
On Error Resume Next
Application.DisplayAlerts = False
Manager = Application.inputbox(Prompt:="Please enter a manager.", Title:="Pick A Manager Name", Type:=1)
On Error GoTo 0
Application.DisplayAlerts = True
If Manager = "" Then
Exit Sub
ElseIf Manager <> Ben, Cameron, Chris, Martin, Peter Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & Manager
End If
End Sub

Although a Sub name same as built in ones are not recommended, you can do what you are after like below.
First you need to change the InputBox Type to 2 (String), since you are comparing with String. Then you should make a function to check if the input is part of a Manager List.
Sub inputbox()
On Error Resume Next
Dim Manager As String
Manager = Application.inputbox(Prompt:="Please enter a manager name:", Title:="Pick A Manager Name", Type:=2)
If Manager <> "" Then
If IsManager(Manager) Then
MsgBox "Your input was " & Manager
Else
MsgBox "Incorrect Name, pick a new one!"
End If
End If
End Sub
Private Function IsManager(sTxt As String) As Boolean
Dim aManagers As Variant, oItem As Variant, bAns As Boolean
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
bAns = False
For Each oItem In aManagers
If LCase(oItem) = LCase(Trim(sTxt)) Then
bAns = True
Exit For
End If
Next
IsManager = bAns
End Function
UPDATE (Improved version suggested by Simon1979):
Private Function IsManager(sTxt As String) As Boolean
On Error Resume Next
Dim aManagers As Variant
aManagers = Array("Ben", "Cameron", "Chris", "Martin", "Peter")
IsManager = Not IsError(Application.WorksheetFunction.Match(Trim(sTxt), aManagers, 0))
End Function

Haven't used the InputBox with Excel but I imagine it will be very similar to the Access one. I use the below method to validate inputbox:
Dim strM as string
EnterManager:
strM = InputBox("Enter Manager.")
If StrPtr(strM) = 0 Then 'Cancel was pressed
' Handle what to do if cancel pressed
Exit Sub
ElseIf Len(strM) = 0 Then 'OK was pressed with nothing entered
MsgBox "You must enter a Manager."
GoTo EnterBuyer
End If
To add your criteria you could add on another If, I'm not sure you can use the approach you have for checking the list of names. Also don't understand how you compare a long Manager with a list of names Ben, Cameron, Chris, Martin, Peter, unless they are assigned variables, in which case I would suggest adding prefixes so it is more obvious such as lBen as opposed to strBen so you can easily see the difference in variable type.
If strM <> "Ben" And strM <> "Cameron" And strM <> "Chris" And strM <> _
"Martin" And strM <> "Peter" Then
MsgBox "Incorrect Name, pick a new one!"
Else
MsgBox "Your input was " & strM
End If

Related

To convert string to double in UFT/QTP

I am trying to convert string to double in UFT but It shows the output without decimal point. below is the code for reference.
vStr = "1000000.589765"
msgbox Typename(vStr)
strV1=CDBL(formatNumber(vStr,4))
msgbox Typename(strV1)
print strV1
Output: 1000000589765
Note that without formatNumber, its not working.
Yet another implementation using DotNetFactory. Just an another thought. I am not denying to use CDbl. But worth to give a shot.
'Test Code
Dim strConvertedCode
strConvertedCode = ConvertDataType("1000000.589765","Double")
If strConvertedCode <> null Then
Msgbox strConvertedCode
End If
Public Function ConvertDataType(ByVal SourceData,ByVal ConversionDataType)
'Initialization of variables
Dim objDotNetFactory
Dim strConvertedData : strConvertedData = null
Dim strSystemNamespace
'Determine the destination data type
Select Case UCase(ConversionDataType)
Case "DOUBLE"
strSystemNamespace = "System.Double"
'Implement further for your data types
'Reference https://msdn.microsoft.com/en-us/library/ms228360(v=vs.90).aspx
Case Default
Set objDotNetFactory = DotNetFactory.CreateInstance("System.Int32")
End Select
Set objDotNetFactory = DotNetFactory.CreateInstance(strSystemNamespace)
'Check the dot net factory instance is successful
If Not IsObject(objDotNetFactory) Then
Reporter.ReportEvent micWarning,"Data type convertor","Conversion from String to " & ConversionDataType & " failed, Since DotNetFactory instance was not created."
ConvertDataType = strConvertedData
Exit Function
End If
strConvertedData = objDotNetFactory.Parse(SourceData)
ConvertDataType = strConvertedData
End Function

Warn before sending Outlook message

My Outlook Address book by default storing e-mail addresses in the combination of upper and lower case letters, in that case below code is not working for me. Please advise.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim Recipients As Outlook.Recipients
Dim recip As Outlook.Recipient
Dim i
Dim prompt As String
On Error Resume Next
' use lower case for the address
' LCase converts all addresses in the To field to lower case
Checklist = "firstname.lastname#domain.com"
Set Recipients = Item.Recipients
For i = Recipients.Count To 1 Step -1
Set recip = Recipients.Item(i)
If InStr(LCase(recip), LCase(Checklist)) Then
prompt$ = "You sending this to this messgae to Treasurer " & Item.To & ". Are you sure you want to send it?"
If MsgBox(prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check Address") = vbNo Then
Cancel = True
End If
End If
Next i
End Sub

IOException Was Unhandled Error Help for Newbie

You'll have to excuse me for a repeat question but I just can't seem to understand the responses others have been posting. My coding skills are very limited (barely a year in vb 2006 and vs 2010)
I know that the sr has opened too many of the same file but I cant figure out a fix for it. Explaining it to me in simple concepts would be very helpful. Once again sorry for the newby-ness.
Project Explanation: Create a bowling league stats keeper. cmdRegisterBowler adds bowler name to a dat file (bowlers.dat). cmdEnterScores will write name and stats to games.dat file.
Private Sub cmdRegisterBowler_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdRegisterBowler.Click
'BOWLER REGISTRATION
Dim Person As String
Dim Team As String
txtName.Text.ToUpper()
txtTeam.Text.ToUpper()
Person = txtName.Text
Team = txtTeam.Text
If Person <> "" And Team <> "" Then
If IsInFile(Person & " " & Team) = True Then
MessageBox.Show(Person & " is already in the file.", "Error")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
Else
'swb = stream writer bowlers file
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
txtName.Clear()
txtTeam.Clear()
txtName.Focus()
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Private Sub cmdEnterScores_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEnterScores.Click
'SCORE ENTRY
Dim Person As String
Dim Team As String
Dim Score1 As Double
Dim Score2 As Double
Dim Score3 As Double
Dim Average As Double
Dim Display As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
Dim Total As Double
Person = txtName2.Text
Team = txtTeam2.Text
Score1 = Val(txtFirstGame.Text)
Score2 = Val(txtSecondGame.Text)
Score3 = Val(txtThirdGame.Text)
Total = Score1 + Score2 + Score3
Average = Total / 3
Dim swb As IO.StreamWriter = IO.File.AppendText("bowlers.dat")
'Checks for blank entries
If Person <> "" Then
'Checks to see if person is registered
If IsNotInFile(Person) Then
Dim Response As Integer
' Displays a message box with the yes and no options to register bowler.
Response = MsgBox(Prompt:="The bowler you have entered is currently not registered. Would you like to do so?", Buttons:=vbYesNo)
'Yes button was selected. Bowler is then registered to bowlers.dat
If Response = vbYes Then
''swb = stream writer bowlers file
swb.WriteLine(Person & " " & Team)
swb.Close()
MessageBox.Show(Person & " has been added to the file.", "Information Added")
'The no button was selected. Focus is set to bowler registration group box
Else : Response = vbNo
txtName2.Clear()
txtTeam2.Clear()
txtFirstGame.Clear()
txtSecondGame.Clear()
txtThirdGame.Clear()
txtName.Focus()
End If
'If no then clears score entry group box and sets focus back to bowler registr
txtName.Clear()
txtName.Focus()
Else
'Write scores to games.dat file
'swg = stream writer games file
Dim swg As IO.StreamWriter = IO.File.AppendText("games.dat")
swg.WriteLine(Name & " " & Team & " " & Score1 & " " & Score2 & " " & Score3)
swg.Close()
MessageBox.Show(Person & "'s stats added to the file.", "Information Added")
txtName.Clear()
txtName.Focus()
Dim Display2 As String = "{0,-10} {1,10} {2,20} {3,10} {4,10} {5,10} {6,10}"
lstDisplay.Items.Add(String.Format(Display2, Person, Team, Score1, Score2, Score3, Total, Average))
End If
Else
MessageBox.Show("You must enter a name.", "Information Incomplete")
End If
End Sub
Function IsNotInFile(ByVal person As String) As String
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual <> person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
End Function
Heres all my code. Thanks for any help in advance.
I haven't used Visual Basic in quite a while, but I believe the solution is simple.
Basically, your interactions with the System.IO library are currently very optimistic. You should always wrap IO interactions within a TRY...CATCH...END TRY block.
Check it out here: MSDN Example of StreamReader.ReadLine
To illustrate more clearly my meaning, I've altered one of your functions here:
Function IsInFile(ByVal person As String) As String
Try
If IO.File.Exists("bowlers.dat") Then
Dim sr As IO.StreamReader = IO.File.OpenText("bowlers.dat")
Dim individual As String
Do Until sr.EndOfStream
individual = sr.ReadLine
If individual = person Then
Return True
sr.Close()
End If
Loop
sr.Close()
End If
Return False
Catch ie as IOException
MessageBox.Show("Failed to search for " & person & " in file.", "Error")
Return false
End Try
End Function
I'd apply similar logic to surround all your interactions with Files within your code. I'd also recommend against using MessageBox to report errors -- it's okay for small projects, but for anything larger you're going to want to look up using a logging framework. Or build a debug console into your application that you can selective turn on or off via configuration.

How to identify between ok and cancel button in inputbox

Hi Hi I have to write a code where if the user clicks enters something in the input box it should proceed further.If it doesnot enter any value it should throw back the same question again again.This i have already achieved,but my problem is when user click on CANCEl it agains asks the same question whereas it ishould exit .I am very new to VB Script .Plz help me how to handle these buttons?Below is my existing code
Do while x=0
strAnswer = InputBox("Please enter the file extension * For all files:", _
"File Extension")
If strAnswer = "" Then
MsgBox"You must enter an extension."
Else
a=strAnswer
Exit Do
End If
Loop
intRow = 2
'strFileName = "T:\public\Madhumita\New.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
'objWorkbook.SaveAs(strFileName)
objExcel.Cells(1, 1).Value = "Folder"
objExcel.Cells(1, 2).Value = "File Name"
objStartFolder = "T:\public\Madhumita\Madhu"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
If a="*" Then
For Each objFile in colFiles
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
Next
else
For Each objFile in colFiles
m=objFSO.GetExtensionName( objFile.Path )
If m=a Then
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
End If
Next
End If
objExcel.Range("A1:B1").Select
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
Sub SaveAs()
Application.Dialogs(xlDialogSaveAs).Show
End Sub
objExcel.Quit
MsgBox "Done"
You need to deal with (at least) three cases - InputBox() returns:
an empty value (Empty, vbEmpty) because the user pressed Cancel or closed the dialog
an empty string ("") or a string of blanks (" ")
a (hopefully) valid string
In code:
Option Explicit
Do While True
Dim vInp : vInp = InputBox("ee")
WScript.Echo TypeName(vInp)
Select Case True
Case IsEmpty(vInp)
WScript.Echo "Abort"
Exit Do
Case "" = Trim(vInp)
WScript.Echo "Try again"
Case Else
WScript.Echo "Work with " & vInp
Exit Do
End Select
Loop
sample output:
String
Try again
Empty
Abort
String
Work with aaa
Sorry to say, but the Docs just lie:
If the user clicks OK or presses ENTER, the InputBox function returns
whatever is in the text box. If the user clicks Cancel, the function
returns a zero-length string ("").
It should be:
... If the user clicks Cancel, the function returns an empty value
(TypeName Empty, VarType vbEmpty).
For InputBox(), you can use the default value to determine if the user clicked Cancel or if they clicked OK or hit Enter to continue without entering a value:
Sub Get_TIN()
TIN = Trim(InputBox("Enter the provider TIN:", "Provider TIN", "ex. 123456789"))
If TIN = "" Then 'When CANCEL is clicked because "TIN" will be empty.
MsgBox "You pressed Cancel. Program will now end.", vbExclamation + vbOKOnly, "Macro End"
Exit Sub
End If
If IsEmpty(TIN) = False Then 'When OK is clicked or Enter pressed because default text will be stored. Next, set TIN to "".
TIN = ""
End If
End Sub
I'm using VBS and my investigation into cancel/ok revealed the following:
Cancel returns an empty string AND a zero length string - same thing you say?, apparently not.
Ok returns a zero length string only.
I use the code below to differentiate.
if IsEmpty(nmbr) then 'cancel button pressed ?
nmbr = "x"
end if
if not IsEmpty(nmbr) then 'ok button pressed ?
if len(nmbr) = 0 then
nmbr = "ok"
end if
end if

how to make sure that all textbox are filled before saving in VB 6.0

I'm new to vb and trying to figure things out via searching the net or asking colleagues but now I hit a dead end. I want to have my program to make sure that all my textboxes are filled before saving into the db.
Here is my code:
Private Sub CmdSave_Click()
Set rs = New ADODB.Recordset
With rs
.Open "Select * from table1", cn, 2, 3
If LblAdd_Edit.Caption = "ADD" Then
If MsgBox("Do you want to save this new rocord?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
.AddNew
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Else
If MsgBox("Do you want to save this changes?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
Do While Not .EOF
If LvList.SelectedItem.Text = !Type Then
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Exit Do
Else
.MoveNext
End If
Loop
End If
End With
Form_Activate
Save_Cancel
End Sub
I was trying to add the following
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
MsgBox("All Fields Required", vbCritical, "Error") = vbOK: Exit Sub
When I run the program I get a compile error
function or call on the left-hand side of assignment must return a variant or object. I use that msgbox function all the time but now its the line I get an error
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
If MsgBox("All Fields Required", vbCritical, "Error") = vbOK Then Exit Sub
Here is a generic solution. It uses a function to check each textbox on the form and demonstrates using the function. I also compare the text length rather than the text to an empty string because (in general) numeric comparisons are faster than string comparisons.
Private Sub Command1_Click()
If ValidateTextFields Then
MsgBox "Your changes have been saved."
Else
MsgBox "All fields are required."
End If
End Sub
Private Function ValidateTextFields() As Boolean
Dim ctrl As Control
Dim result As Boolean
result = True 'set this to false if a textbox fails
For Each ctrl In Me.Controls
If TypeOf ctrl Is TextBox Then
If Len(ctrl.Text) = 0 Then
result = False
Exit For 'bail on the first failure
End If
End If
Next ctrl
ValidateTextFields = result
End Function
In VB6, you can use Trim() function so that spaces not considered as characters.
If (Trim$(txtGOSID.Text) = "") Then
msgBox "Please provide input.", vbExclamation
With the $ sign, Trim() returns a String value directly; without the $
sign, Trim() returns a Variant with a sub-type of String.

Resources