Week 6. Assessment 2 Do Loops Custom Functions.

25
Week 6

Transcript of Week 6. Assessment 2 Do Loops Custom Functions.

Week 6

Assessment 2 Do Loops Custom Functions

Sub SheetCounter()

MsgBox ("There are " & Worksheets.Count & " worksheets in this _ workbook")

End Sub

Sub CreateStaffList()

Dim r As WorksheetDim 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

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

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

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

Sub DWL()Dim x As Integerx = 0Do While x < 5 Debug.Print x x = x + 1LoopMsgBox "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!)

Sub MarkEmptyCells()

Do While IsEmpty(ActiveCell) With ActiveCell .Value = "This cell is blank" .Font.Bold = True .Offset(1, 0).Activate End WithLoop

MsgBox "We are out of the loop. That's all folks"

End Sub

Sub DLW()Dim x As Integerx = 0Do Debug.Print x x = x + 1Loop While x < 5End 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.

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

   

Sub DUL()Dim x As Integerx = 0Do Until x > 5 Debug.Print x x = x + 1LoopEnd Sub

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

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

Sub one()Do While Not IsEmpty(ActiveCell)ActiveCell.Offset(1, 0).SelectLoopEnd Sub

Sub two()DoActiveCell.Offset(1, 0).SelectLoop While Not IsEmpty(ActiveCell)End Sub

Sub three()Do Until IsEmpty(ActiveCell)ActiveCell.Offset(1, 0).SelectLoopEnd Sub

Sub four()DoActiveCell.Offset(1, 0).SelectLoop Until IsEmpty(ActiveCell)End Sub

Sub five()Selection.End(xlDown).SelectActiveCell.Offset(1, 0).SelectEnd Sub

 

 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

Do Loop

Leap Years (part 1)

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

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

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

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 - deductionsEnd Function

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

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) ^ nperEnd 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 SingleDim fv As Singlefv = (pr * (1 + rate) ^ nper)compound = fv - prEnd Function

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”)

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 …

You can call functions with the following code:

Application.WorksheetFunction.FunctionName(arg1,arg2)

Error Handling Conversion Functions