Presentation is loading. Please wait.

Presentation is loading. Please wait.

Week 6.  Assessment 2  Do Loops  Custom Functions.

Similar presentations


Presentation on theme: "Week 6.  Assessment 2  Do Loops  Custom Functions."— Presentation transcript:

1 Week 6

2  Assessment 2  Do Loops  Custom Functions

3 Sub SheetCounter() MsgBox ("There are " & Worksheets.Count & " worksheets in this _ workbook") End Sub Sub CreateStaffList() Dim r As Worksheet Dim s As Worksheet Worksheets.Add.Name = "StaffList" Set r = Worksheets("net_pay") Set s = Worksheets("StaffList") r.Range("G2:G10").Copy s.Range("A1:A10") End Sub

4 Produce a macro that, if run on a new workbook will: Ask the user how many stores and how many products they wish to monitor Create new worksheets so that there are enough for one for each week (4?) and a summary sheet Name each work sheet appropriately Ensure each sheet is set up ready for the user to input data, with formulas to calculate the row and column totals

5  Add formulas in the summary sheet to “pull through” the data from the previous sheets  Extend the summary sheet to hold other useful calculations (eg. best performing store / product)  Allow the user to input the number of weeks the workbook will be used for  Ask the user which month/ year the workbook is intended for and save the workbook using month/year as a name

6  There are four varieties of the Do loop: Do While... Loop Do... Loop While Do Until... Loop Do... Loop Until

7 Sub DWL() Dim x As Integer x = 0 Do While x < 5 Debug.Print x x = x + 1 Loop MsgBox "bye" End Sub x < 5 is the condition which initially evaluates to True The key word “Loop” returns control to the Do While statement which re- evaluates the condition; there should be a statement somewhere before the statement which changes the condition otherwise the loop will run ‘forever’  (Note: Ctrl + Break should terminate most runaway loops; if not Ctl Alt + Delete and end Excel - and lose unsaved work!)

8 Sub MarkEmptyCells() Do While IsEmpty(ActiveCell) With ActiveCell.Value = "This cell is blank".Font.Bold = True.Offset(1, 0).Activate End With Loop MsgBox "We are out of the loop. That's all folks" End Sub

9 Sub DLW() Dim x As Integer x = 0 Do Debug.Print x x = x + 1 Loop While x < 5 End Sub There is no condition at this stage so the statements to be executed happen at least once. The Statement returns control to the Do statement only if the condition evaluates to true.

10 Sub DLU() Dim x As Integer x = 0 Do Debug.Print x x = x + 1 Loop Until x > 5 End Sub Sub DUL() Dim x As Integer x = 0 Do Until x > 5 Debug.Print x x = x + 1 Loop End Sub

11 Sub markEmptyCells_until() Do Until not IsEmpty(ActiveCell) ActiveCell.Value = "Default value" ' whatever ActiveCell.Font.Bold = True 'makes it easy to see ActiveCell.Offset(1, 0).Select Loop MsgBox "We are out of the loop. That's all folks" End Sub

12  All the following programs select the first empty cell in the same column below the active cell, four illustrating the use of Do loops; the fifth uses the statement that is recorded when you press Ctrl and the Down Arrow key

13 Sub one() Do While Not IsEmpty(ActiveCell) ActiveCell.Offset(1, 0).Select Loop End Sub Sub two() Do ActiveCell.Offset(1, 0).Select Loop While Not IsEmpty(ActiveCell) End Sub Sub three() Do Until IsEmpty(ActiveCell) ActiveCell.Offset(1, 0).Select Loop End Sub Sub four() Do ActiveCell.Offset(1, 0).Select Loop Until IsEmpty(ActiveCell) End Sub Sub five() Selection.End(xlDown).Select ActiveCell.Offset(1, 0).Select End Sub

14  Loops can contain control statements such as If Then or other loops  If statements can contain loops  You can break out of a loop if necessary by using the Exit Do keyword

15  Do Loop  Leap Years (part 1)

16  You are probably familiar with using built-in functions like SUM, AVERAGE and IF. With VBA, you can create your own functions, uniquely tailored to your needs. function functionname() -- function code goes here -- end function

17  Let's say you want to create a function that calculates how much your Net Pay is after deductions. The function would involve these values:  GrossPay: how much you earn before deductions  Income Tax as a percentage  National Insurance as a percentage  Pension Fund as a percentage

18  NetPay is how much you take home after IncomeTax, National Insurance and Pension Fund contributions have been deducted.  The maths would look like this:  Deductions =  (GrossPay * IncomeTax) + (GrossPay * NI) + (GrossPay * Pension)  NetPay = GrossPay - Deductions

19 Function NetPay _ (GrossPay As Double, IncomeTax _ As Double, NI As Double, Pension As_ Double) As Double Dim Deductions As Double Deductions = (GrossPay * IncomeTax) +_ (GrossPay * NI) +(GrossPay * Pension) NetPay = GrossPay - deductions End Function

20  You can use functions in the same way as you use Excel functions. Your VBA functions will appear in the “User Defined Functions” category

21  A function called myFV, (so it doesn’t conflict with the inbuilt Excel function FV) which works out the value of an investment after compound interest has been added, i.e. its future value. Function myFV(pr As Single, rate As Single, nper As Integer) As_ Single myFV = pr * (1 + rate) ^ nper End Function  On the other hand you might also want a function that works out just the compound interest i.e. minus the principal. Function Compound(pr As Single, rate As Single, nper As Integer) as Single Dim fv As Single fv = (pr * (1 + rate) ^ nper) compound = fv - pr End Function

22 LCase() returns lower case version of a string LCase(“ABCD”) UCase() returns upper case version of a string UCase(“abcd”) Len() returns number of characters in a string Len(“ABCDE”) Trim() removes leading and trailing spaces from a string Trim(“ ABC “) LTrim() removes leading spaces from a string LTrim(“ ABC”) RTrim() removes trailing spaces from a string RTrim(“ABC “) Left() returns leftmost characters of a string Left(“ABCDEF”,3) Right() returns rightmost characters of a string Right(“ABCDEF,3”) StrComp() compares two strings for equivalence and returns the integer result of comparison: 0 if strings are equal, -1 if strings are different StrComp(“ABC,”abc”) Val() returns numeric value of a string in data type appropriate to the format of the argument. Val(“123.45”)

23  You can create a macro to call the FunctionWizard or Insert Function dialog – which would save a few seconds each time you run it:  ActiveCell.FunctionWizard  You would then choose which function to use …

24  You can call functions with the following code: Application.WorksheetFun ction.FunctionName(arg1,arg2)

25  Error Handling  Conversion Functions


Download ppt "Week 6.  Assessment 2  Do Loops  Custom Functions."

Similar presentations


Ads by Google