1 / 65

InputBox Function

InputBox Function. InputBox: predefined Visual Basic dialog box with a prompt, text box, and OK and Cancel buttons Used to obtain data from the user and return it as a a string value to the calling procedure Displayed by using InputBox function: InputBox(prompt, title) Example:

zlhna
Download Presentation

InputBox Function

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. InputBox Function • InputBox: predefined Visual Basic dialog box with a prompt, text box, and OK and Cancel buttons • Used to obtain data from the user and return it as a a string value to the calling procedure • Displayed by using InputBox function: InputBox(prompt, title) • Example: strMax = InputBox("Enter max number", "Max Choice") • If user clicks OK button, text entered is returned. • If user clicks Cancel button, empty string is returned. (Be sure to check for empty text.) Visual Basic - Chapter 6

  2. Demo: DisplayIt When the Display button is clicked, request text with InputBox. If text is received, display it; if not, display “No data entered.” Private Sub cmdDisplay_Click() Dim strMsg As String Dim strPrompt As String strPrompt = "Enter text:" strMsg = InputBox(strPrompt, "Input Box") If strMsg = "" Then lblMsg.Caption = "No data entered." Else lblMsg.Caption = strMsg End If End Sub Visual Basic - Chapter 6

  3. Also available as Until condition infinite loop: use Ctrl-Break to stop always executes at least once Do... Loop Statement • Looping or Iterating -> repeating one or more statements • Variety of statements in Visual Basic to allow code to be repeated • Do Loops are useful for repeating while some condition continues or until some condition occurs [Note: must change condition or will loop forever] • Syntax: Do While condition statements Loop Do statements Loop While condition Visual Basic - Chapter 6

  4. Do... Loop Practice • New form; bring up Immediate window; run code snippets below in Form_Load: Dim intNum As Integer Debug.Print "start" intNum = 21 Do While intNum < 25 Debug.Print intNum intNum = intNum + 1 Loop Debug.Print "end" Dim intNum As Integer Debug.Print "start" intNum = 26 Do While intNum < 25 Debug.Print intNum Loop Debug.Print "end" start end start 21 22 23 24 end Dim intNum As Integer Debug.Print "start" intNum = 26 Do Debug.Print intNum Loop While intNum < 25 Debug.Print "end" Dim intNum As Integer Debug.Print "start" intNum = 21 Do Debug.Print intNum intNum = intNum + 1 Loop While intNum < 25 Debug.Print "end" start 26 end start 21 22 23 24 end Visual Basic - Chapter 6

  5. comment out statement that changes the while condition More Do... Loop Practice • Run this code snippet in Form_Load: Dim intNum As Integer Debug.Print "start" intNum = 21 Do While intNum < 25 Debug.Print intNum ‘intNum = intNum + 1 Loop Debug.Print "end" start 21 21 21 21 21 21 21 21 21 21 ... INFINITE LOOP: Use Ctrl-Break to stop Visual Basic - Chapter 6

  6. Note different indentation. Demo: DiceRoll – Doubles Only Modify DiceRoll to display the next “roll” of doubles each time the Roll button is clicked. Dim intDie1 As Integer Dim intDie2 As Integer Do intDie1 = Int(6 * Rnd) + 1 intDie2 = Int(6 * Rnd) + 1 Loop While intDie1 <> intDie2 lblDie1.Caption = intDie1 lblDie2.Caption = intDie2 Visual Basic - Chapter 6

  7. Common Uses for Do Loops • Repeat while something is true • Repeat game while user says “Y” to “Another Game?” prompt • Repeat until something occurs • Keep adding user-entered numbers until zero is entered • Keep processing grades until grade of Z is entered • Repeat while some value is invalid Dim strNum As String strNum = InputBox("Guess?", "Guess Entry") Do While Not IsNumeric(strNum) strNum = InputBox("Please enter number between 1 and 50", "Invalid Entry") Loop Note: expanded prompt. Visual Basic - Chapter 6

  8. or Loop While Not (strMsg = "STOP") Demo: DisplayIt – Repeat Text Entry/Display Modify code in the Display button in DisplayIt to keep accepting/ displaying text until STOP is entered. Private Sub cmdDisplay_Click() Dim strMsg As String Dim strPrompt As String strPrompt = "Enter text (STOP to quit):" Do strMsg = InputBox(strPrompt, "Input Box") If strMsg = "" Then lblMsg.Caption = "No data entered." Else lblMsg.Caption = strMsg End If Loop While strMsg <> "STOP" End Sub Visual Basic - Chapter 6

  9. Sentinels • Sentinel: specific value that is used to signify desire to repeat/stop a process (loop) • Examples: • Y to play game again • 0 to stop adding numbers • Z to quit entering grades • Declare sentinels as constants to make it easy to change the value, as Private Const strLASTGRADE As String = "Z" Visual Basic - Chapter 6

  10. Now: Change the terminator string to END. Problem  Prompt still says STOP… Demo: DisplayIt – Sentinel Constant Modify code in the Display button in DisplayIt to keep accepting/ displaying text until STOP is entered. Private Sub cmdDisplay_Click() Const strTERMINATOR As String = "STOP" Dim strMsg As String Dim strPrompt As String strPrompt = "Enter text (STOP to quit):" Do strMsg = InputBox(strPrompt, "Input Box") If strMsg = "" Then lblMsg.Caption = "No data entered." Else lblMsg.Caption = strMsg End If Loop While strMsg <> strTERMINATOR End Sub Visual Basic - Chapter 6

  11. Concatenating Strings • Concatenate: connect together • Use the ampersand (&) to store multiple “pieces” in a string variable • Examples: lblLevel.Caption = "Level" & intLevelNum lblMsg.Caption = strLastName & ", " & strFirstName strFormula = intNum1 & " + " & intNum2 & " = " strList = strList & ", " & strNewItem • Eliminates need for multiple labels on forms and allows build up of strings for messages Visual Basic - Chapter 6

  12. Demo: DisplayIt – Sentinel in Prompt Change the prompt in the Display button in DisplayIt to concatenate the terminator constant with the other text. Private Sub cmdDisplay_Click() Const strTERMINATOR As String = "END" Dim strMsg As String Dim strPrompt As String strPrompt = "Enter text (" & strTERMINATOR & " to quit):" Do strMsg = InputBox(strPrompt, "Input Box") If strMsg = "" Then lblMsg.Caption = "No data entered." Else lblMsg.Caption = strMsg End If Loop While strMsg <> strTERMINATOR End Sub Visual Basic - Chapter 6

  13. Using Accumulators • Accumulator: numeric variable used to store a value that accumulates (gets added to) at run-time • Used for sums and totals • Updating an accumulator: accumulatorvariable = accumulatorvariable + incrementvalue • Examples: intSum = intSum + intNextNum curTotal = curTotal + curPrice • Always initialize accumulators, usually to zero • Commonly used in Do Loops with sentinel to stop accumulating Visual Basic - Chapter 6

  14. Demo: DisplayIt – Display Sum of Numbers Modify DisplayIt to add up a series of numbers entered by the user and display the sum when a terminator of –1 is entered. Problem: terminator (-1) was added into the sum. Change the If statement to fix this. Visual Basic - Chapter 6

  15. Demo: DisplayIt – Display Sum - Code Code for Display button is shown below: Private Sub cmdDisplay_Click() Const strTERMINATOR As String = "-1" Dim dblNum As Double, dblSum As Double Dim strMsg As String Dim strPrompt As String strPrompt = "Enter a number to add (" & strTERMINATOR & " to quit):" dblSum = 0 lblMsg.Caption = "" Do strMsg = InputBox(strPrompt, "Input Box") If strMsg <> strTERMINATOR And IsNumeric(strMsg) Then dblNum = strMsg dblSum = dblSum + dblNum End If Loop While strMsg <> strTERMINATOR lblMsg.Caption = "Sum = " & dblSum End Sub Visual Basic - Chapter 6

  16. Review 6-3: Average Score As user enters test scores (integers), display a running count and average. When Enter Scores button is clicked, loop on InputBox (until value of –1 is entered) to get score and display running count and average. Use a counter for the number of scores and an accumulator for the average. Be sure to reset count/average and clear out labels when Enter Scores button is clicked (again). Visual Basic - Chapter 6

  17. after successful entry after 5 unsuccessful tries Exercise 6-1: Password Modify Password to give user a specified number of tries (initially, 5) to get the password right. Visual Basic - Chapter 6

  18. Exercise 6-3: Bowling Scores Allow user to enter a series of bowling scores, ending with -1. Keep track of the high and low scores. When Enter Scores button is clicked, loop on InputBox (until value of –1 is entered) to get scores and keep track of high and low scores. Display high/low scores when Statistics button is clicked. Be sure to clear label when Enter Scores button is clicked. Be sure to test with multiple clicks of Enter Scores: -Click Statistics button first [No high/low]. -Click Enter Scores multiple times and enter: *No entries *1 entry [should be high and low] *2 entries [1 should be high, the other low] *More than 2 entries [check for validity] Visual Basic - Chapter 6

  19. Review 6-4: Unique Random Numbers Display how many iterations it takes to generate three unique random numbers between 1 and a user-specified max. Be sure to test with a low max (like, 2) and a high max (like, 100). Change to iterate until all 3 numbers are the same. Note differences in iteration cycles. Visual Basic - Chapter 6

  20. Manipulation of Text Data • Very strong aspect of Visual Basic • Business applications use text data extensively • Applications much more user-friendly if no worries about case or exact matching • Examples: • Ways to type yes,Yes,YES,yEs,yeS,YEs,YeS,yES • Manipulating case: as, saving private ryan  Saving Private Ryan • Changing name forms: as, Cheryl M. Davis  Davis, Cheryl M. or initials CMD • Replacing strings of text: as, Y2K millenium bug (98  1998) Visual Basic - Chapter 6

  21. String Conversion Functions - 1 • LCase(string) • Returns the text in string in all lowercase characters • Example: strFav = “My Dad” lblFav.Caption = LCase(strFav) my dad • UCase(string) • Returns the text in string in all uppercase characters • Example: strFav = “My Dad” lblFav.Caption = UCase(strFav)MY DAD Visual Basic - Chapter 6

  22. String Conversion Functions - 2 • StrConv(string, conversiontype) returns string converted to case according to conversion argument • Example: strTitle = "saving private ryan" lblDVD.Caption = StrConv(strTitle, vbProperCase)  Saving Private Ryan Predefined constants: vbLowerCase all lowercase vbUpperCase all uppercase vbProperCase  first letter in words uppercase, rest lowercase Visual Basic - Chapter 6

  23. Demo: DisplayText Display text characters (in a label) as they are entered (in a text box). Private Sub txtMsg_Change() dim strMsg As String dim strNewMsg As String strMsg = txtMsg.Text strNewMsg = strMsg lblDisplay.Caption = strNewMsg End Sub Instead: Display text all uppercase: strNewMsg = LCase(strMsg) Instead: Display text all lowercase: strNewMsg = UCase(strMsg) Instead: Display text in propercase: strNewMsg = StrConv(strMsg, vbProperCase) Visual Basic - Chapter 6

  24. Len Function • Len(string) returns a count of the number of characters in string • Example: strDVD = "Saving Private Ryan" intDVDLength = Len(strDVD) 19 Note: Length includes spaces and other special characters. Visual Basic - Chapter 6

  25. Demo: DisplayText – Display Length of Text Modify DisplayText to display the length of the text entered. Add a label (lblLength) to display the length of text as the user enters it: Length = n Where n is the length of the text in the text box. lblLength.Caption = "Length = " & Len(strMsg) Visual Basic - Chapter 6

  26. String Manipulation Functions - 1 • Left(string, length) • returns length number of characters beginning at string left • Example: strSeason = “Summer” lblSeason.Caption = Left(strSeason, 3)  Sum • Right(string, length) • returns length number of characters beginning at string right • Example: strSeason = “Summer” lblSeason.Caption = Right(strSeason, 4)  mmer Visual Basic - Chapter 6

  27. String Manipulation Functions - 2 • Mid(string, start, length) • returns length number of characters beginning with the start character in string •  Example: strSeason = “Summer” lblSeason.Caption = Mid(strSeason, 3, 2) mm Visual Basic - Chapter 6

  28. Private Sub cmdChangeText_Click() Dim strMsg As String = txtMsg.Text lblBeg.Caption = Left(strMsg, 3) lblEnd.Caption = Right(strMsg, 2) lblMid.Caption = Mid(strMsg, 2, 4) End Sub Demo: DisplayText – Only Part of Text Modify DisplayText to show the beginning, middle, and end of the text entered. • When the user clicks the ChangeText button: • Display first 3 characters in lblBeg. • Display last 2 characters in lblEnd. • Display characters 2-5 in lblMid. Be sure to clear out the labels when the text in the text box changes. Visual Basic - Chapter 6

  29. String Manipulation - Mid Statement • Mid(string1, start, length) = string2 • replaces length characters in string1, beginning with start character, and using characters in string2 •  Example: strMonth = “Jan 1999” Mid(strMonth, 5, 4) = “2000”  Jan 2000 Visual Basic - Chapter 6

  30. Demo: DisplayText – Replace Characters Modify DisplayText to replace part of the text entered. When the user clicks the ChangeText button, add a label (lblReplace) to display the text entered but replacing characters 2-4 with the text new. Note: Do not change text in the text box. Be sure to clear out the label when the text in the text box changes. Dim strMsg As String strMsg = txtMsg.Text Mid(strMsg, 2, 3) = "new” lblReplace.Caption = strTemp Visual Basic - Chapter 6

  31. InStr Function • InStr(start, string1, string2) • returns starting position of substring string2 in string1, with the search beginning with character start in string1 • returns 0 if string2 is not found in string1 • starts at beginning if no start specified • Examples: strSample = “underneath” intFind = InStr(strSample, “un”)  1 intFind = InStr(6, strSample, “un”)  0 intFind = InStr(4, strSample, “eat”)  7 strSearchYear = “1999” strMonth = “January 1999” intWhereYear = InStr(strMonth, strSearchYear) Mid(strMonth, intWhereYear, 4) = “2000” strMonth  January 2000 Visual Basic - Chapter 6

  32. Exercise 6-4: Initials After the user enters a name, display the initials in uppercase. • Hints: • The first initial is always the leftmost character in the string (Left function). • Find a space (InStr function) and use that position + 1 to locate the other initial (Mid function). • Display in uppercase (UCase function) Note: Entering “madonna” should display M (not MM). Extra Credit: Modify to handle names with more than 2 strings. Visual Basic - Chapter 6

  33. Worksheet 6.1-2: Find And Replace Create and display a new string by replacing every occurrence of one character in an original string of textwith another character. Hint: Loop through the search and replace process repeatedly until InStr returns 0, indicating that there are no more occurrences of the target letter. Visual Basic - Chapter 6

  34. Worksheet 6.1-1: Questions Display questions and keep track of how many questions were asked and how many were answered correctly. Visual Basic - Chapter 6

  35. Looping Structures Based on Counting • Many applications involve some sort of counting: • Display numbers from 1 to 10 • Draw 50 asterisks in a row • Allow password entry 3 times • Ask 50 questions • Check 100 answers Visual Basic - Chapter 6

  36. increments by 1 if no Step clause Note: counter after For and Next must match. • Dim intNumber As Integer • For intNumber = 1 To 10 • MsgBox(intNumber) • Next intNumber • Dim intOdd As Integer • For intOdd = 13 To 1 Step -1 • MsgBox(intOdd) • Next intOdd For... Next Statement • Looping structure that executes until a counter reaches an ending value (automatically updates the counter on each iteration of the loop) • Syntax: For counter = start To end [Step increment] statements Next counter • Examples: display numbers 1 to 10: display odd numbers 13 to 1: Visual Basic - Chapter 6

  37. Demo: Counting Display message boxes with numbers 1 to 10 when user clicks Count button. Then change to display odd numbers from 13 to -1. • Dim intNumber As Integer • For intNumber = 1 To 10 • MessageBox(intNumber) • Next intNumber Try different start, end, increment values. Modify to accept user-specified start, end, and increment values. Dim intNumber As Integer, intStart As Integer Dim intEnd As Integer, intAddTo As Integer 'check for valid integers intStart = txtStart.Text intEnd = txtEnd.Text intAddTo = txtIncr.Text For intNumber = intStart To intEnd Step intAddTo MessageBox (intNumber) Next intNumber Visual Basic - Chapter 6

  38. Exercise 6-7: Sum Calculate the sum of the numbers between two numbers inclusive that the user enters. Sum = 13 + 14 + 15 = 42 Visual Basic - Chapter 6

  39. Review 6-10: Odd Numbers Sum Display the sum of the odd numbers between 1 and a number entered by the user. Note: The value in this example was computed as: 1 + 3 + 5 + 7 = 16. Also note that it doesn’t matter if the user enters an even number, but you should display an error message if the input is not a number or if the number is negative. Visual Basic - Chapter 6

  40. Note: Unlike Round, Format does NOT change the value of the data. Format Function • Format function can be used to format (change the appearance) of numeric output • Syntax: Format(number, "format type") • Format types include: Standard, Currency, Percent • Examples: dblNum = 8789.2345 lblNum.Caption = Format(dblNum, "Standard") 8,789.23 lblNum.Caption = Format(dblNum, "Currency") $8,789.23 dblNum = .566666 lblNum.Caption = Format(dblNum, "Percent") 56.67% • Many other formatting options are available Visual Basic - Chapter 6

  41. Worksheet 6.2-2: Average Allow the user to indicate how many numbers are to be entered and, when the Start button is clicked, display input boxes to accept the numbers. When all the numbers have been entered, display the average. The message should be in the following format: Average of the n numbers is a.aa where n is how many numbers and a.aa is the average, rounded to 2 digits and formatted for display (as, 6,743.47). Visual Basic - Chapter 6

  42. outer For statement inner For statement Nested For Loops • For loop statements may be nested, similar to nested If statements • Example: Display the numbers 1 to 10 each 4 times: For numbers 1 to 10 For a count of 1 to 4 Display the number Next Skip a line Next Visual Basic - Chapter 6

  43. When displaying text that needs fixed-sized characters, use Courier New font. Use concatenation and vbCrLf to force text to a new line. Demo: Square Application Display a matrix of asterisks, using the user-specified number as the width and length of the matrix. Use a nested For loop to create the display. Note: Because you can’t control the height of the lines in the label, your output will not look like a square. Visual Basic - Chapter 6

  44. Demo: Box Application Modify the square application to instead create a rectangle with the length and width specified by the user. Don’t forget to clear the results when either the width or length specification changes. Visual Basic - Chapter 6

  45. Review 6-9: Factorial Display the factorial of an integer entered by the user. Note: Display the factors as you compute the factorial. (The display above shows how to compute a factorial.) Don’t forget to clear out the results when the user enters a new number. Visual Basic - Chapter 6

  46. Character Data Storage • Standard binary representations for characters to facilitate sharing of computer data • Unicode – new 2-byte worldwide character standard • ASCII – 1-byte standard for common characters that uses numbers between 0 and 255 to represent characters • 0 is 48, 1 is 49... 9 is 57 • A is 65, B is 66... Z is 90 • a is 97, b is 98... z is 122 • Asc(string) returns the ASCII code corresponding to the string character, as, Asc("A")  65 • Chr(integer) returns the character corresponding to the ASCII code in integer, as, Chr(98)  b Asc only translates one character. Visual Basic - Chapter 6

  47. Demo: CharASCII Display the character equivalent of a user-entered ASCII code or the ASCII code for a user-entered character. Be sure to: Check for an invalid ASCII value and/or more than 1 character input. Clear out the old display when text box value changes. Private Sub cmdChar_Click() Dim intASCII As Integer If IsNumeric(txtASCII.Text) Then intASCII = txtASCII.Text If intASCII >= 0 And intASCII <= 255 Then lblChar.Caption = Chr(intASCII) Else lblChar.Caption = "Invalid" End If Else lblChar.Caption = "Invalid" End If End Sub Private Sub cmdASCII_Click() If Len(txtChar.Text) = 1 Then lblASCII.Caption = Asc(txtChar.Text) Else lblASCII.Caption = "Invalid" End If End Sub Visual Basic - Chapter 6

  48. Demo: CharASCII - Alphabet Add a label that shows up to 26 characters, starting with the character-equivalent of the ASCII code entered (as, A-Z if 65). Be sure you don’t try to display beyond the ASCII max of 255. ‘new code in cmdChar_Click() Dim intLetter As Integer, intMax As Integer ‘add after this statement: lblChar.Caption = Chr(intASCII) intMax = intASCII + 25 If intMax > 255 Then intMax = 255 For intLetter = intASCII To intMax lbl26Chars.Caption = lbl26Chars.Caption & Chr(intLetter) Next intLetter Visual Basic - Chapter 6

  49. Comparing Strings • When comparing strings using relational operators, ASCII/UNICODE codes are used for evaluation So, "amanda" < "arnold" is true But, "Amanda" < "arnold" is false (uppercase letters have higher ASCII values than lowercase) • To do text compares that ignore case, use StrComp(string1, string2, vbTextCompare) returns: 0 if textually equal -1 if string1 less than string2 +1 if string 1 greater than string2 • Examples: intResult = StrComp("APPLE", "apple", vbTextCompare)  0 (equal) intResult = StrComp("APPLE", "orange", vbTextCompare)  -1 (1st lower) intResult = StrComp("Baby", "apple", vbTextCompare)  1 (1st higher) Visual Basic - Chapter 6

  50. Demo: Compare Strings Allow the user to enter two strings and, ignoring case, display whether the strings are equal or else which one is lower. Use StrComp to compare the strings. Be sure to clear label when text box changes. Dim intResult As Integer intResult = StrComp(txt1stString.Text, txt2ndString.Text, vbTextCompare) If intResult = 0 Then lblResult.Caption = "Strings are equal" ElseIf intResult = -1 Then lblResult.Caption = "First string is lower." Else lblResult.Caption = "Second string is lower." End If Visual Basic - Chapter 6

More Related