SpreadsheetBased Decision Support Systems Chapter 16 Programming Structures

Spreadsheet-Based Decision Support Systems Chapter 16: Programming Structures Prof. Name Position University Name name@email. com (123) 456 -7890

Overview v v v v 16. 1 Introduction 16. 2 If, Then Statements 16. 3 Select, Case 16. 4 Loops 16. 5 Exit Statements and End 16. 6 Applications 16. 7 Summary 2

Introduction v Using If, Then statements for conditional programming, logical checks, and error checking v VBA Select, Case structure v For Loops and Do Loops v Various exit statements and the End statement v Creating a banking account management application using the programming structures described in the chapter 3

If, Then Statements v Logical Checks and Booleans 4

If, Then Statements v If, Then statements allow you to perform the same conditional actions that we learned with the IF function in Excel. v If a condition is met, a certain set of actions is performed, if it is not, another set of actions may be performed instead. v The general format for the If, Then statement is If condition Then action End If 5

If, Then (cont) v The If, Then statement defines the action to performed if the condition is false by using the Else and Else. If statements. v The Else statement allows you to specify the action to be performed if the condition is not met. v The Else. If statement allows you to construct nested If statements. – That is, instead of performing a direct action if the original condition is not met, another If condition is considered. 6

If, Then Example If x < 1000 Then Msg. Box “Your number is smaller than 1000. ” Else. If x < 2000 Then Msg. Box “Your number is greater than 1000 but less than 2000. ” Else Msg. Box “Your number is larger than 2000” End If 7

Logical Checks and Booleans v If, Then statements are also used with logical checks and Boolean variables. v Logical checks include And and Or statements similar to the AND and OR functions we learned in Excel. 8

And Logical Check v The And logical statement requires every condition in the If, Then statement to be true in order for the following action to be performed. v If only one of the conditions is false, the action will not be performed and the following Else or Else. If statement will be read or the If, Then statement will end. v This statement structure is as follows If condition 1 And condition 2 And condition 3 And … Then action 1 Else (or Else. If) action 2 End If 9

Or Logical Check v The Or logical statement requires only one condition in the If, Then statement to be true in order for the following action to be performed. v Every condition would have to be false to skip the following action and read the Else, Else. If, or End If statements. v This statement structure is as follows If condition 1 Or condition 2 Or condition 3 Or … Then action 1 Else (or Else. If) action 2 End If 10

And, Or Example If x < 1000 And x > 500 Then Msg. Box “Your number is between 500 and 1000. ” Else Msg. Box “Your number is smaller than 500 or greater than 1000. ” End If v Here, the And check requires that both conditions be met. v If this is true, then the value of x should be between 500 and 1000, thus the first Message Box is displayed. v However, if either condition is false, then the statement in the second Message Box must be true. 11

And, Or Example (cont) If x > 1000 Or x < 500 Then Msg. Box “Your number is smaller than 500 or greater than 1000. ” Else Msg. Box “Your number is between 1000 and 500. ” End If v Here we can see the difference in using the Or logical check. v With Or, either of the conditions can be true to display the first Message Box. – That is either x can be greater than 1000 or less than 500. v If neither condition is met, then the second Message Box must be true. 12

Using Boolean Variables v If, Then statements are used with Boolean variables to check if their values are True or False. v You can simply use the following two statements If variable = True Then action 1 End If ----------------If variable = False Then action 2 End If 13

Using Boolean Variables (cont) v To check if a Boolean variable is True, you can also just state the name of the variable. – that is, the default value of any Boolean variable is True. v Instead of the first statement in the previous slide, you can just type If variable Then action End If 14

Boolean Example If found Then Msg. Box “The solution has been found. ” Else. If found = False Then Msg. Box “The solution has not been found. ” End If 15

Select, Case v The Select, Case statement is used to list possible situations in which certain actions should be performed. v The general structure of the Select, Case statement gives a particular expression which is to be evaluated and a list of cases of possible values of that expression. Select Case number Case 1 Msg. Box “Your number is 1. ” Case 2 Msg. Box “Your number is 2. ” End Select 16

Select, Case (cont) v We can also give a range of values as a case instance. Select Case number Case 1 To 5 Msg. Box “Your number is in the interval (1, 5). ” Case 6 To 10 Msg. Box “Your number is in the interval (6, 10). ” End Select 17

Select, Case (cont) v There is also an optional Case Else statement which can be used to specify all other cases which are not listed. v The ability to give a range of values as a case instance using the To statement can be extended to string values. Select Case name Case “Adams” To “Henderson” Msg. Box “Please look in files A to H. ” Case “Ignatius” To “Nichols” Msg. Box “Please look in files I to N. ” Case Else Msg. Box “Please look in files N to Z. ” End Select 18

Select, Case (cont) v You may also include some conditions as cases instead of simple instances. v This is useful in replacing several Else. If statements in an If, Then structure. Select Case number < 10 Msg. Box “Your number is less than 10. ” Case number > 10 Msg. Box “Your number is greater than 10. ” End Select 19

Select, Case (cont) v You can place a condition on a range of values using the Is statement. Select Case number Case 1 To 5 Is = number Msg. Box “Your number is in the interval (1, 5). ” Case 6 To 10 Is = number Msg. Box “Your number is in the interval (6, 10). ” Case Else Msg. Box “Your number is greater than 10. ” End Select 20

Loops v For Loops v Do Loops 21

Loops v Loops are programming structures which allow you to repeat a set of actions a certain number of times. v The number of loops can be specified by counting up to (or down to) a certain value. – For, Next – For Each, Next v Or the loops can run continuously while or until a certain condition is met. – Do, While – Do, Until 22

For Loops v The For, Next and For Each, Next loops are used to repeat a loop while counting up toward to down to a certain number. – We refer to them both generally as For Loops. v We perform the counting using some simple index variable such as i or a counting variable such as count or iteration. – These variables are integer data types. 23

For, Next v The more common of these two structures is the For, Next loop. v The structure of this loop is as follows For counter = start To end actions Next counter 24

For, Next (cont) v There is also a Step parameter used with this loop. v The Step value specifies how much the counter variable should increase or decrease during each loop. 25

For, Next (cont) v If you want to count up towards a number, the Step value should be positive and the start value should be less than the end value. For i = 1 to 10 Step 2 actions Next i v If you wish to count down to a number, the Step value should be negative and the start value should be greater than the end value. For i = 10 to 1 Step -1 actions Next i 26

For Each, Next v The For Each, Next loop works almost identically to the For, Next loop. v The only difference is that For Each, Next is counting a certain number of objects in a group of objects. – That is objects are counted rather than using a counter variable. 27

For Each, Next (cont) v For example, if we want to count the number of worksheets in the current workbook, we could declare a worksheet variable ws and use the following For Each, Next loop with some count variable. For Each ws In Active. Workbook. Worksheets count = count + 1 Next 28

Do Loops v There are two main Do Loops – Do, While – Do, Until v These Do Loops perform a set of actions repeatedly while or until a condition is met. v There are two main structures for these loops – Specify While or Until condition before actions – Specify While or Until condition after actions 29

Do Loop Structures v In the structure below, a while condition is considered before a set of actions will be performed. Do While count < 10 actions count = count + 1 Loop v In the second structure, the set of actions will be performed and then the while condition will be checked before the actions are repeated. Do actions count = count + 1 Loop While count < 10 30

While vs Until v The difference between looping while the condition is met and until the condition is met is important to note. – For the Do, While loop, if the condition is true this signals the loop to repeat the actions. – However, for the Do, Until loop, if the condition is true, this signals the loop to stop repeating the actions. 31

While vs Until (cont) v Compare the values generated by the following two loops. Do While count <= 10 x = 2*x count = count + 1 Loop v For this first loop, assuming the value of the count variable is initialized to be 1, the condition will be met the first time (1 <= 10) and the next 10 times. v The action (x = 2*x, again assuming x is initially 1) will therefore be repeated 10 times yielding the final values of – x = 2^10 – count = 11 32

While vs Until (cont) Do Until count = 10 x = 2*x count = count + 1 Loop v This second loop, however, will stop repeating when count reaches 10 (but not including 10). v v Thus yielding final values of – x = 2^9 – count = 10 33

Boolean Variables in Do Loops v Do Loops can also be used with Boolean variables. – That is, the Boolean variable can be used as the condition for the Do, While or Do, Until loops. v These conditions usually imply some nested If, Then statements which would change the value of the Boolean variable once a certain result is found. 34

Boolean Variables (cont) Do While found = False actions If x > 100 Then found = True End If Loop v Here we are performing some actions while a certain result is still not found. v Once the found variable is set to True, the While condition is no longer met and the loop ends. 35

Exit Statements and End v Exiting Procedures v Exiting Loops v Ending the Program 36

Exit Statements v As we develop and run longer programming structures such as nested If, Then statements and Do Loops, we may want a way to exit the current set of actions at any time. v We may also want to use this option while running any sub procedure or function procedure. v VBA provides several Exit Statements which allow current actions to stop and moves the program to following code. v We will usually use these statements with the If, Then structure. 37

Exiting Procedures v To exit a procedure we use either Exit Sub or Exit Function depending on if we are currently running a sub procedure or function procedure respectively. v When Exit Function is stated, the function procedure will stop being executed and the program will return to the point in the code from which the function was called. v When the Exit Sub statement is used, the sub procedure will stop being executed, and if the sub was called from another sub, the program will return to this sub and begin executing the next line of code. 38

Exit Sub and Exit Function Example v Here, we perform simple error checking with a Divide function. Sub Calculations() x = Input. Box(“Enter x value. ”) y = Input. Box(“Enter y value. ”) value = Divide(x, y) If value = “none” Then Exit Sub End If Msg. Box “x divided by y is “ & Divide(x, y) End Sub ------------------------Function Divide(a, b) If b = 0 Then Divide = “none” Exit Function End If Divide = a / b End Function 39

Exiting Loops v To exit a loop we use Exit For and Exit Do depending on if we are currently in a For, Next or For Each, Next loop or in a Do, While or Do, Until loop. v Similar to the above exit statements, Exit For will stop executing a For, Next or For Each, Next loop and move to the next line of code after the Next statement. v The Exit Do code will stop executing a Do Loop and move to the next line of code after the Loop statement. 40

Exit For Example Sub Organize() Set Start. Cell = Range(“A 1”) For i = 1 to 100 Start. Cell. Offset(i, 0). Value = i * (i – 1) If i * (i – 1) > 50 Then Msg. Box “The calculation values exceed the limit. ” Exit For End If Next i End Sub 41

Exit Do Example Do x = x^2 If x mod 5 = 0 Then Msg. Box “The number “ & x & “ is divisible by 5. ” Exit Do End If x=x+1 Loop Until x >100 42

Exiting Loops (cont) v These statements can also be used with nested loops. v The exit statement will apply to the inner most loop in which it is used. For i = 1 to 100 For j = 1 to 50 Start. Cell. Offset(i, j). Value = i + j If i + j > 60 Then Exit Do End If Next j Next i 43

Ending the Program v We can stop executing the entire program by using the End statement. – Just as the End Sub, End Function, End If, and End With statements end the execution of the enclosed lines of code, the End statement will stop executing all code and exit all loops and procedures. v This can be a useful function if there is some significant condition or requirement that must be met before the program can function correctly. 44

End Example v In this code, the Username sub procedure is called to prompt the user for a username. v Then the Find. File function procedure is called to find the filename listed for the given username in a particular database. Sub Main() Call Username Call Find. File(username) If filename = “” Then Msg. Box “No file was found for this user. ” End If Call Edit. Record End Sub v If the file is found, then the record for this user can be edited, however if no file is found which matches the username given there is no need to continue running this program as this is a necessary requirement for all further actions. 45

Basic Error Checking v Possible Error: User Input – User input is usually assigned to a variable. – This variable must have been declared previously with a specific data type. – An error can occur if the data that the user provides as input does not match the data type already assigned to the variable. v The Variant data type – A temporary Variant data type variable can be used to assign to any input that is provided by the user v An Error Checking Solution: Is. Numeric and CInt functions – The Is. Numeric function returns the value True or False depending on whether or not the variable or expression is a numeric data type – The CInt conversion function will ensure that this variable has the data type needed for subsequent calculations 46

Basic Error Checking (cont’d) Dim Temp. Input As Variant, x As Integer Temp. Input = Input. Box(“Please enter a number. ”) If Is. Numeric(Temp. Input) = True Then x = CInt(Temp. Input) End If v Similarly, the Is. Date and CDate functions can be used for date input. v (See Appendix B for a detailed discussion of other error checking solutions. ) 47

Applications v Banking Account Management 48

Description v This program stores deposits, withdrawals, and the current balance of a user’s banking account. v The user can record a new deposit or new withdrawal or they can sum current deposits or withdrawals. v Each time a new deposit or withdrawal is made, the balance is updated. v There is also a minimum balance requirement of $100 for this account. 49

Preparation v There are only two worksheets for this program. – “Account Welcome” – “Account” v Like any welcome sheet, the “Account Welcome” sheet has a program title and description. – We have also added a Start button; this button will be associated with a Main sub procedure 50

Figure 16. 1 51

“Account” Sheet v The “Account” sheet is where the program actions will occur. – The record of account transactions is shown with the date and description of each transaction. – Each button is associated with the action stated in the button caption. – The Exit button, as in all of our applications, will bring the user back to the welcome sheet. 52

Figure 16. 2 53

Procedures v We will have a New. Deposit and New. Withdrawal procedure associated with the first button options. – In each of these procedures we will be adding a new user-supplied value to the “Amount” column. v We will also need to update the balance in both procedures by calling an Update. Balance function procedure. v We will also need two summing procedures which we will call Sum. Deposits and Sum. Withdrawals. 54

Procedures (cont) v The first, and most important organizational sub procedure will be the Main sub procedure. – This macro will be associated with the Start button on the welcome sheet. – We will clear previous sum values from their respective ranges, set any range variables, initialize any other variables if needed, and hide the welcome sheet and bring the user to the “Account” sheet. v There will also be a short Exit. Account procedure to be assigned to the Exit button. 55

Variables v We will have a deposit and withdrawal variable to insert the new values and update the balance. – We will use a value variable (declared as a variant data type) to receive user input before assigning values to the deposit and withdrawal variables; this is in order to perform error checking. v We will have sum. Dep and sum. With variables to calculate the respective sums. 56

Variables (cont) v We will have two range variables to identify the “Amount” and “Balance” columns. – We call them Account. Start and Balance. Start. v We will later use an integer counter i for our loops and a response variable (declared as a variant data type) in a Msg. Box function. 57

Workbook_Open v This time we improve our code by using a worksheet variable, ws, and a For Each, Next loop. Private Sub Workbook_Open() For Each ws In Active. Workbook. Worksheets If ws. Name = "Account Welcome" Then ws. Visible = True Else ws. Visible = False End If Next End Sub 58

Variables (cont’d) v We define all previously discussed variables, including the worksheet variable, publicly as follows. Public deposit As Double, withdrawal As Double, sum. Dep As Double, _ sum. With As Double, Account. Start As Range, Balance. Start As Range, _ ws As Worksheet, Value As Variant, i As Integer, response As Variant 59

Main v In preparation for coding we have named the two ranges in which the sum values will be calculated. – “Deposit. Sum” and “Withdrawal. Sum” respectively Sub Main() Range("Deposit. Sum"). Clear. Contents Range("Withdrawal. Sum"). Clear. Contents Set Account. Start = Worksheets("Account"). Range("D 5") Set Balance. Start = Worksheets("Account"). Range("F 5") sum. Dep = 0 sum. With = 0 Worksheets("Account"). Visible = True Worksheets("Account Welcome"). Visible = False Worksheets("Account"). Activate End Sub 60

Exit. Account v The navigational procedure for the Exit button is Sub Exit. Account() Worksheets("Account Welcome"). Visible = True Worksheets("Account"). Visible = False End Sub 61

Summing Procedures v For each Sum button we will look through every entry of the “Amount” column until the end of the column is reached. – We do this using a Do, Until loop, Account. Start range variable, and the Offset property. v For each entry we check if the value is a withdrawal or deposit and update our respective sum variables. – We do this using If, Then statements. v We will use the counter variable i for the loop. 62

Sum. Deposits Sub Sum. Deposits() i=1 Do Until Account. Start. Offset(i, 0). Value = "" If Account. Start. Offset(i, 0). Value > 0 Then sum. Dep = sum. Dep + Account. Start. Offset(i, 0). Value End If i=i+1 Loop Range("Deposit. Sum"). Value = sum. Dep End Sub 63

Sum. Withdrawals Sub Sum. Withdrawals() i=1 Do Until Account. Start. Offset(i, 0). Value = "" If Account. Start. Offset(i, 0). Value < 0 Then sum. With = sum. With + Account. Start. Offset(i, 0). Value End If i=i+1 Loop Range("Withdrawal. Sum"). Value = sum. With End Sub 64

New. Deposit v The first line of code will be to ask the user for the amount of the new deposit. v We will temporarily set the value variable equal to our Input. Box function so that we can perform error checking on the input. Sub New. Deposit() value = Input. Box("Please enter amount to deposit. ", _"New Deposit", 150#) 65

New. Deposit (cont) v To perform the error checking, we will use the Is. Numeric function with the value variable to see if the user entered a numerical data type. v If so, then we can continue running the sub procedure, however if the value is not numeric then we cannot continue with the procedure actions. – We therefore inform the user of their error using a simple Message Box and then use Exit Sub. If Is. Numeric(value) = False Then Msg. Box "You have not entered a numerical value. Please try again. " Exit Sub End If v If the user has provided a numeric value then we assign this value to the deposit variable. deposit = value 66

New. Deposit (cont) v We now insert this value into the “Amount” column using the Account. Start range variable and the End property. v We also format this new row of the table by changing the background color of the appropriate cells. With Account. Start. End(xl. Down). Offset(1, 0). Value = deposit. Interior. Color. Index = 0 End With Range(Account. Start. End(xl. Down). Offset(0, -3), _ Account. Start. End(xl. Down). Offset(0, -2)). Interior. Color. Index = 0 Balance. Start. End(xl. Down). Offset(1, 0). Interior. Color. Index = 0 67

New. Deposit (cont) v The only action left to perform is to update the balance by calling the Update. Balance function. v After those actions are complete we can simply inform the user that they may enter a date and description for the new entry with a Message Box. Call Update. Balance(deposit, "D") Msg. Box "You may now enter the date and description of your “ & _ & “deposit into the table. " 68

New. Deposit (cont) v We can additional option to continue adding more new deposits by using the Msg. Box function and response variable. v We prompt the user if they want to enter another deposit and set the Message Box buttons to be vb. Yes. No. v The Msg. Box function is assigned to the response variable so we check the value of the response variable and perform the related actions. 69

New. Deposit (cont) v We will use another If, Then statement to see if the response was “Yes”, which is equal to the VB Constant vb. Yes, and call the New. Deposit sub procedure again if it is. v Otherwise we will just end the sub. …. response = Msg. Box("Would you like to enter another deposit? ", _ vb. Yes. No, "Another Deposit? ") If response = vb. Yes Then Call New. Deposit End If End Sub 70

New. Withdrawal v The New. Withdrawal procedure will be very similar. v We do not give the option to create another new withdrawal here, but you can add this later. v The only main changes are using the withdrawal variable instead of deposit and entering the value in the table as a negative number. 71

New. Withdrawal (cont) Sub New. Withdrawal() value = Input. Box("Please enter amount to withdraw. ", "New withdrawal", 150#) 'error checking If Is. Numeric(value) = False Then Msg. Box "You have not entered a numerical value. Please try again. " Exit Sub End If withdrawal = value 'insert into table and format new row With Account. Start. End(xl. Down). Offset(1, 0). Value = -withdrawal. Interior. Color. Index = 0 End With Range(Account. Start. End(xl. Down). Offset(0, -3), _ Account. Start. End(xl. Down). Offset(0, -2)). Interior. Color. Index = 0 Balance. Start. End(xl. Down). Offset(1, 0). Interior. Color. Index = 0 'update balance Call Update. Balance(withdrawal, "W") End Sub 72

Update. Balance v There will be two parameters for this function. – The deposit or withdrawal value. – And a simple letter signifying if this is a deposit “D” or withdrawal “W”. – Notice that these variables are passed when the function is called from the above two procedures. – The function declaration refers to these two parameters simply as x and y. v We can then use a Select, Case statement to check the value of the y parameter. – In the case that it is “D” we will add the deposit value to the last entry of the “Balance” column. – In the case that it is “W” we will subtract the withdrawal value from the last entry of the “Balance” column. 73

Update. Balance (cont) v We must also perform one more check in the case that a withdrawal is made: we must ensure that the $100 balance requirement will still be met after the withdrawal is made. v We use an If, Then statement to check the result of this calculation. – If the withdrawal will result in a balance less than $100, we do not perform the transaction. – The user is informed that their balance is too low, the initial entry to the “Amount” column is cleared, and the function is exited using the Exit Function statement. – However, if the requirement will still be met, then we update the balance and tell the user they can enter the date and description for the withdrawal. 74

Update. Balance (cont) Function Update. Balance(x, y) Select Case y Case "D" Balance. Start. End(xl. Down). Offset(1, 0). value =_ Balance. Start. End(xl. Down). value + x Case "W" If Balance. Start. End(xl. Down). value - x < 100 Then Msg. Box "This withdrawal cannot be made due to the $100 “ & _ & “balance requirement. " Account. Start. End(xl. Down). Clear. Contents Exit Function End If Balance. Start. End(xl. Down). Offset(1, 0). value = _ Balance. Start. End(xl. Down). value - x Msg. Box "You may now enter the date and description of your “ & _ & “withdrawal into the table. " End Select End Function 75

Application Conclusion v The procedures are now complete. v We assign them to their respective buttons and test the macro. v The application is finished. 76

Summary v If, Then statements allow you to perform conditional actions. If a condition is met, a certain set of actions is performed; if it is not, another set of actions may be performed instead. v Use the Select, Case statement to list possible situations in which certain actions should be performed. v Loops are programming structures that allow you to repeat a set of actions a certain number of times. v VBA provides several Exit Statements that allow current actions to stop and moves the program to ensuing code. 77

Additional Links v (place links here) 78
- Slides: 78