Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 3 pps

50 431 0
Microsoft Excel VBA Programming for the Absolute Beginner Second Edition phần 3 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

‘—————————————————————————————————- ‘Function calls to determine the number of die displaying each value. ‘—————————————————————————————————- numOnes = GetNumOnes numTwos = GetNumTwos numThrees = GetNumThrees numFours = GetNumFours numFives = GetNumFives numSixes = GetNumSixes ‘—————————————————————- ‘Call functions for the result of the hand. ‘—————————————————————- result = IsNothingOrStraight(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsOnePair(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsTwoPair(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsThreeOfAKind(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsFourOfAKind(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsFiveOfAKind(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) result = IsFullHouse(numOnes, numTwos, numThrees, _ numFours, numFives, numSixes, result) Range(“C12”).Value = result End Sub The line continuation (_) character tells VBA that I really want just one line of code, but I need to type it on more than one line in the text editor. Make sure there is a single space between the last character and the underscore before proceeding to the next line. The function procedures GetNumOnes(), GetNumTwos(), GetNumThrees(), GetNumFours(), GetNumFives(), and GetNumSixes() are called from the DisplayResult() sub procedure and they determine the number of dice with a particular value. These functions use numerous If/Then code TRICK 89 Chapter 3 • Procedures and Conditions 90 structures to check the values of the dice stored in the second row of the spreadsheet (cells B2 through F2). The random number function Rnd() generated these values earlier in the program. A variable is then incremented if its associated value is found in a spreadsheet cell. These functions effectively determine how many dice show the value 1, 2, 3, 4, 5, or 6. Private Function GetNumOnes() As Integer ‘Determine the number of dice displayed with a value of 1 Dim numOnes As Integer If Range(“B2”).Value = 1 Then numOnes = numOnes + 1 If Range(“C2”).Value = 1 Then numOnes = numOnes + 1 If Range(“D2”).Value = 1 Then numOnes = numOnes + 1 If Range(“E2”).Value = 1 Then numOnes = numOnes + 1 If Range(“F2”).Value = 1 Then numOnes = numOnes + 1 GetNumOnes = numOnes End Function Private Function GetNumTwos() As Integer ‘Determine the number of dice displayed with a value of 2 Dim numTwos As Integer If Range(“B2”).Value = 2 Then numTwos = numTwos + 1 If Range(“C2”).Value = 2 Then numTwos = numTwos + 1 If Range(“D2”).Value = 2 Then numTwos = numTwos + 1 If Range(“E2”).Value = 2 Then numTwos = numTwos + 1 If Range(“F2”).Value = 2 Then numTwos = numTwos + 1 GetNumTwos = numTwos End Function Private Function GetNumThrees() As Integer ‘Determine the number of dice displayed with a value of 3 Dim numThrees As Integer If Range(“B2”).Value = 3 Then numThrees = numThrees + 1 If Range(“C2”).Value = 3 Then numThrees = numThrees + 1 If Range(“D2”).Value = 3 Then numThrees = numThrees + 1 If Range(“E2”).Value = 3 Then numThrees = numThrees + 1 If Range(“F2”).Value = 3 Then numThrees = numThrees + 1 GetNumThrees = numThrees End Function Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Private Function GetNumFours() As Integer ‘Determine the number of dice displayed with a value of 4 Dim numFours As Integer If Range(“B2”).Value = 4 Then numFours = numFours + 1 If Range(“C2”).Value = 4 Then numFours = numFours + 1 If Range(“D2”).Value = 4 Then numFours = numFours + 1 If Range(“E2”).Value = 4 Then numFours = numFours + 1 If Range(“F2”).Value = 4 Then numFours = numFours + 1 GetNumFours = numFours End Function Private Function GetNumFives() As Integer ‘Determine the number of dice displayed with a value of 5 Dim numFives As Integer If Range(“B2”).Value = 5 Then numFives = numFives + 1 If Range(“C2”).Value = 5 Then numFives = numFives + 1 If Range(“D2”).Value = 5 Then numFives = numFives + 1 If Range(“E2”).Value = 5 Then numFives = numFives + 1 If Range(“F2”).Value = 5 Then numFives = numFives + 1 GetNumFives = numFives End Function Private Function GetNumSixes() As Integer ‘Determine the number of dice displayed with a value of 6 Dim numSixes As Integer If Range(“B2”).Value = 6 Then numSixes = numSixes + 1 If Range(“C2”).Value = 6 Then numSixes = numSixes + 1 If Range(“D2”).Value = 6 Then numSixes = numSixes + 1 If Range(“E2”).Value = 6 Then numSixes = numSixes + 1 If Range(“F2”).Value = 6 Then numSixes = numSixes + 1 GetNumSixes = numSixes End Function The function procedures IsNothingOrStraight(), IsOnePair(), IsTwoPair(), IsThreeOfAKind(), IsFourOfAKind(), IsFiveOfAKind(), IsSixOfAKind(), IsFullHouse() are called from the Display Result() sub procedure, and effectively score the hand and return a string result. 91 Chapter 3 • Procedures and Conditions 92 Each of these functions tests for a particular score (for example, one pair, two pair, and so on) indicated by the function name. These functions use If/Then/Else structures with numerous conditional statements. I said earlier in the chapter there would be an excessive use of conditionals—at this point, it can’t be helped much, but I have used a line continua- tion character (_) in an effort to make the code easier to read. Consider the IsNothingOrStraight() function procedure. The six conditionals in the first If/Then/Else structure are all linked with logical And. This means that all conditionals must be true if the block of code within the first If/Then statement is to be executed. If the num- ber of occurrences of each die’s value is equal to or less than one, a nested If/Then/Else code structure is then used to determine if the hand is a “6 High Straight”, a “6 High”, or a “5 High Straight” . If one of these conditional statements is true, then the function is assigned the value of one of the aforementioned strings which is returned to the calling procedure. If none of the conditionals are true, the original result is returned. Similar logic applies to the remaining functions and their determination of a score. You should study each function carefully noting the use of logical operators, parentheses, and If/Then/Else code structures. Parentheses can be used to change the order of operator execution in VBA expressions. For example the conditional statement (5 > 4 Or 6 > 3) And 7 < 3 evaluates to false whereas the expression 5 > 4 Or 6 > 3 And 7 < 3 evaluates to true. Private Function IsNothingOrStraight(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If (numOnes <= 1) And (numTwos <= 1) And (numThrees <= 1) And _ (numFours <= 1) And (numFives <= 1) And (numSixes <= 1) Then If (numSixes = 1) And (numOnes = 0) Then IsNothingOrStraight = “6 High Straight” ElseIf (numSixes = 1) And (numOnes = 1) Then IsNothingOrStraight = “6 High” Else IsNothingOrStraight = “5 High Straight” End If Else IsNothingOrStraight = result End If End Function TRICK Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Private Function IsOnePair(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If (numOnes = 2) And (numTwos <= 1) And (numThrees <= 1) And _ (numFours <= 1) And (numFives <= 1) And (numSixes <= 1) Then IsOnePair = “Pair of Ones” ElseIf (numOnes <= 1) And (numTwos = 2) And (numThrees <= 1) And _ (numFours <= 1) And (numFives <= 1) And (numSixes <= 1) Then IsOnePair = “Pair of Twos” ElseIf (numOnes <= 1) And (numTwos <= 1) And (numThrees = 2) And _ (numFours <= 1) And (numFives <= 1) And (numSixes <= 1) Then IsOnePair = “Pair of Threes” ElseIf (numOnes <= 1) And (numTwos <= 1) And (numThrees <= 1) And _ (numFours = 2) And (numFives <= 1) And (numSixes <= 1) Then IsOnePair = “Pair of Fours” ElseIf (numOnes <= 1) And (numTwos <= 1) And (numThrees <= 1) And _ (numFours <= 1) And (numFives = 2) And (numSixes <= 1) Then IsOnePair = “Pair of Fives” ElseIf (numOnes <= 1) And (numTwos <= 1) And (numThrees <= 1) And _ (numFours <= 1) And (numFives <= 1) And (numSixes = 2) Then IsOnePair = “Pair of Sixes” Else IsOnePair = result End If End Function Private Function IsTwoPair(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If (numOnes = 2 And numTwos = 2) Or _ (numOnes = 2 And numThrees = 2) Or _ (numOnes = 2 And numFours = 2) Or _ (numOnes = 2 And numFives = 2) Or _ (numOnes = 2 And numSixes = 2) Or _ (numTwos = 2 And numThrees = 2) Or _ (numTwos = 2 And numFours = 2) Or _ (numTwos = 2 And numFives = 2) Or _ 93 Chapter 3 • Procedures and Conditions 94 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition (numTwos = 2 And numSixes = 2) Or _ (numThrees = 2 And numFours = 2) Or _ (numThrees = 2 And numFives = 2) Or _ (numThrees = 2 And numSixes = 2) Or _ (numFours = 2 And numFives = 2) Or _ (numFours = 2 And numSixes = 2) Or _ (numFives = 2 And numSixes = 2) Then IsTwoPair = “Two Pair” Else IsTwoPair = result End If End Function Private Function IsThreeOfAKind(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If (numOnes = 3 And numTwos < 2 And numThrees < 2 And numFours < 2 _ And numFives < 2 And numSixes < 2) Then IsThreeOfAKind = “Three Ones” ElseIf (numOnes < 2 And numTwos = 3 And numThrees < 2 And _ numFours < 2 And numFives < 2 And numSixes < 2) Then IsThreeOfAKind = “Three Twos” ElseIf (numOnes < 2 And numTwos < 2 And numThrees = 3 And _ numFours < 2 And numFives < 2 And numSixes < 2) Then IsThreeOfAKind = “Three Threes” ElseIf (numOnes < 2 And numTwos < 2 And numThrees < 2 And _ numFours = 3 And numFives < 2 And numSixes < 2) Then IsThreeOfAKind = “Three Fours” ElseIf (numOnes < 2 And numTwos < 2 And numThrees < 2 And _ numFours < 2 And numFives = 3 And numSixes < 2) Then IsThreeOfAKind = “Three Fives” ElseIf (numOnes < 2 And numTwos < 2 And numThrees < 2 And _ numFours < 2 And numFives < 2 And numSixes = 3) Then IsThreeOfAKind = “Three Sixes” Else IsThreeOfAKind = result End If End Function Private Function IsFourOfAKind(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If numOnes = 4 Then IsFourOfAKind = “Four Ones” ElseIf numTwos = 4 Then IsFourOfAKind = “Four Twos” ElseIf numThrees = 4 Then IsFourOfAKind = “Four Threes” ElseIf numFours = 4 Then IsFourOfAKind = “Four Fours” ElseIf numFives = 4 Then IsFourOfAKind = “Four Fives” ElseIf numSixes = 4 Then IsFourOfAKind = “Four Sixes” Else IsFourOfAKind = result End If End Function Private Function IsFiveOfAKind(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If numOnes = 5 Then IsFiveOfAKind = “Five Ones” ElseIf numTwos = 5 Then IsFiveOfAKind = “Five Twos” ElseIf numThrees = 5 Then IsFiveOfAKind = “Five Threes” ElseIf numFours = 5 Then IsFiveOfAKind = “Five Fours” ElseIf numFives = 5 Then IsFiveOfAKind = “Five Fives” ElseIf numSixes = 5 Then IsFiveOfAKind = “Five Sixes” Else 95 Chapter 3 • Procedures and Conditions 96 IsFiveOfAKind = result End If End Function Private Function IsFullHouse(numOnes As Integer, numTwos As Integer, _ numThrees As Integer, numFours As Integer, numFives As Integer, _ numSixes As Integer, result As String) As String If (numOnes = 3 And numTwos = 2) Or (numOnes = 3 And numThrees = 2) Or _ (numOnes = 3 And numFours = 2) Or (numOnes = 3 And numFives = 2) Or _ (numOnes = 3 And numSixes = 2) Or (numTwos = 3 And numOnes = 2) Or _ (numTwos = 3 And numThrees = 2) Or (numTwos = 3 And numFours = 2) Or _ (numTwos = 3 And numFives = 2) Or (numTwos = 3 And numSixes = 2) Or _ (numThrees = 3 And numOnes = 2) Or (numThrees = 3 And numTwos = 2) Or _ (numThrees = 3 And numFours = 2) Or (numThrees = 3 And numFives = 2) Or _ (numThrees = 3 And numSixes = 2) Or (numFours = 3 And numOnes = 2) Or _ (numFours = 3 And numTwos = 2) Or (numFours = 3 And numThrees = 2) Or _ (numFours = 3 And numFives = 2) Or (numFours = 3 And numSixes = 2) Or _ (numFives = 3 And numOnes = 2) Or (numFives = 3 And numTwos = 2) Or _ (numFives = 3 And numThrees = 2) Or (numFives = 3 And numFours = 2) Or _ (numFives = 3 And numSixes = 2) Or (numSixes = 3 And numOnes = 2) Or _ (numSixes = 3 And numTwos = 2) Or (numSixes = 3 And numThrees = 2) Or _ (numSixes = 3 And numFours = 2) Or (numSixes = 3 And numFives = 2) Then IsFullHouse = “Full House” Else IsFullHouse = result End If End Function Figure 3.13 shows an example of the Poker Dice game board after two rolls of the dice. That concludes Poker Dice. It really is a pretty simple program. The difficulty lies in following the logic of the large number of conditions contained in the expressions with the If/Then/Else code structures. Some of the procedures are longer than I normally write them because of the number of conditionals involved and I have not yet discussed loops. As you may have already guessed, these procedures can be simplified significantly with the use of different programming structures and techniques. You will look at a couple of these structures in the next chapter. Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Chapter Summary In this chapter, you covered a considerable amount of material on some of the tools required to help you build a strong programming foundation. You started by taking an in-depth look at procedures in VBA; specifically, event, sub, and function procedures. You learned how to use and build these procedures while considering the procedure’s scope, available parameters, and return values (function procedures). You even learned how to build new function pro- cedures to use within formulas created in the Excel application. Finally, you saw two new code structures, If/Then/Else and Select/Case and you learned how to use Boolean logic within conditional expressions so a program could branch off in different directions in terms of code execution. In essence, you learned how to write a program that can make simple decisions. 97 Chapter 3 • Procedures and Conditions Figure 3.13 The Poker Dice game board after two rolls. 98 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition C HALLENGES 1. Draw a simple image of a smiley face using MS Paint then load the image into an Image control placed on a worksheet in Excel. Using the MouseDown() event pro- cedure of the Image control, write a program that displays a message to the user every time the user clicks on the image. The message should tell the user if he or she clicked on the eyes, nose, mouth, or face of the image and which button they used. The message can be displayed with a message box, or in a Label control, or on the spreadsheet. 2. Write a function procedure in VBA that returns the square root of a number. The function should be made available to the Excel application. 3. Write a sub procedure in VBA that either adds, subtracts, multiplies, or divides two numbers. The procedure should be called by another sub procedure that collects the two numbers from the user and asks the user which mathematical operation is desired. The calling procedure should also output the result, displaying the original values and the answer. 4. Add a few Check Box controls or Option Button controls to a worksheet, then use a Select/Case code structure in a sub procedure that outputs a message to the user telling them which box or option has been selected. 5. Add some features to the Poker Dice program. For example, keep a record of a user’s session (n games) by outputting the results of each game to a spreadsheet column off the game board. Use a static variable to track the row number of the cell you output the results to. You can also assign point values to each hand based on its value and track the user’s point total for a session of Poker Dice. To make getting a good hand more difficult, you can create additional dice images using new colors (blue, green, and so on). [...]... Sub 114 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition After variable declarations, the values in column A of the worksheet are loaded into the array with a simple For/ Next loop The For/ Next loop nested in the Do-Loop is just as it was in the BubbleSort() procedure, except now the Cells property has been replaced with the array named myArray The looping variable in the For/ Next... transpose the values, the looping variables I and J are now used to access the opposite index (i.e., I is used for the row index; J is used for the column index) in the Cells property; however, the array transArray uses the indices as in the previous For/ Next loop These nested For/ Next loops effectively transpose the values, as shown in Figure 4.5 116 Microsoft Excel VBA Programming for the Absolute Beginner, ... contents of the clipboard onto the worksheet 122 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Another option is to use the AutoFill() method by specifying the destination range The term Destination is a named argument predefined for the AutoFill() method in VBA Named arguments allow the programmer to pass values to a function without having to worry about the order of the arguments,... simplifies the task considerably Validation with the InputBox() Function In the Chapter 2 project, the program asked the user to input his or her name and birthday The program assumed the user would enter the information in the proper format For the user’s name, the desired format was first name-space-last name and for the user’s birthday, a date format of month, day, and year (e.g., 3/ 4/86 or 3- 4-1986) The. .. removed using the Trim() function so extra spaces before or after the names are forgiven The length of the resulting string is then stored in the strLength variable for use in the subsequent For/ Next loop The For/ Next loop tests the leftmost character for equality to a space before removing this character If the character is a space then a variable keeping track of the number of spaces in the string is... representation of the Do-Loop to use, ask yourself whether you need the code inside the loop to execute at least once If you do, then put the conditional at the end The choice of While or Until depends on the logic of the conditional expression Do While (condition) ‘Block of code executes only if condition is true Loop Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition 102 Beware... spreadsheet cell formatted with a large, easy to read font 2 The user interface shall contain a Command Button control for initiating the program 124 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition 3 The user interface shall contain a timer that counts down to zero from 60 seconds (displaying each second) The timer shall be written to a spreadsheet cell 4 The user interface... range using a For/ Next loop Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition 106 For I = 1 To 10 For J = 4 To 7 Cells(I, Chr(64 + J)).Value = I * J Next J Next I HIN T The looping structures discussed so far are not the best choice for looping through a range of cells—even though doing so is a simple enough task A better looping structure for handling this task is the For/ Each... ValidateName() name procedure returns false, or the user hits the cancel button (InputBox() returns an empty string) on the input box 108 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition The ValidateName() function procedure accepts the string entered by the user as input and tests for the number of spaces inside the string Private Function ValidateName(userName As String)... at the different looping structures available in VBA before moving on to arrays Specifically, this chapter will cover: • Do Loops • For Loops • Input Validation • Arrays • Multi-Dimensional Arrays • Dynamic Arrays • Recording Macros • The Forms Toolbar Controls 100 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Project: Math Game The Math Game program is a natural choice for . simple decisions. 97 Chapter 3 • Procedures and Conditions Figure 3. 13 The Poker Dice game board after two rolls. 98 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition C HALLENGES 1 Macros • The Forms Toolbar Controls CHAPTER 100 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition Project: Math Game The Math Game program is a natural choice for programming. variable 1 03 Chapter 4 • Loops and Arrays 104 Microsoft Excel VBA Programming for the Absolute Beginner, Second Edition The required keywords are For, To, and Next. To keep track of the number

Ngày đăng: 12/08/2014, 16:21

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan