Excel practise... If and While!
If you're keen to go over how to use IF ELSEIF END IF statements in VBA, there's a great tutorial with practical examples on Conditional Statements at FunctionX. We're going to focus our attention for the moment on looping in VBA with the While loop.
Try creating a new workbook, add a new user form with a few buttons (btnWhile1, btnWhile2). Put the following code behind one of your buttons (with the button name "Count to 10"):
'We're going to make up a variable to count through our while-loop:
Dim count as Integer
count = 0
While count < 10
MsgBox("Count is :" & count)
count = count + 1
Wend
Run your code by clicking on your button and make sure it does what you expect it to do! Now, have a go at the following:
- Call your second button "Even Numbers" and see if you can add a similar function that only counts even numbers (Hint: start with the exact code above).
- Call a third button "Odd Numbers" and see if you can create a similar function that counts the odd numbers less than 10.
- Modify both your buttons so that they only count numbers up to 8. Check that they work correctly.
- Add a new button called Colourise. When you've got lots of information in a worksheet, it's sometimes really helpful to use an off-white (or pastel) colour for every second row (it helps to differentiate the rows of information). Using the Cells function (eg: Cells(count,1) ), see if you can create code that colours every second cell up to row 100 with an off-white colour of your choice!
- Modify your Colourise button so that it colours every second Row instead of just the one cell.
0 Comments:
Post a Comment
<< Home