510 likes | 718 Views
12. Visual Basic If Statements and Do Loops. Open 12b-datastart.xlsm. If statements. We have seen how to use IF statements in formulas in Excel IF statements can also be used in Visual Basic but they have a different format The basic format is: If a cell has a value greater than 10 Then
E N D
If statements • We have seen how to use IF statements in formulas in Excel • IF statements can also be used in Visual Basic but they have a different format • The basic format is: If a cell has a value greater than 10Then Make the font bold ElseIfcell has a value less than 10 Then Make the font italic EndIf • Begin with Macro Recorder and then edit
Excel produces code for all aspects of the fontWe are only concerned with .FontStyle = “Bold”
We only want Excel to do this when the cell value is greater than 10
Excel should evaluate the cell and give it a bold font as it has a value above 10
Want to add another condition that if value is less than 10 give it Italic font
Challenge • Edit the Visual Basic code so that there are three conditions • If ActiveCell.Value > 20 Then • Font style should be “Bold” • ElseIfActiveCell.Value > 15 Then • Font style should be “Italic” • ElseIfActiveCell.Value < 15 Then • Font style should be “Bold Italic” • EndIf
Do Loops • We can get Excel to do something repeatedly by setting up a Do … Loop Until … • Rather than evaluating one cell at a time we may want to work through all the cells in a row • We can tell Excel to evaluate the cell and move to the next cell • We then get Excel to repeat this until the next cell is blank
After the If statement we want to select the cell in the next column
We want Excel to Do this repeatedly until the next cell is empty
Excel repeats the command and evaluates each cell within the row
Challenge • Edit the Visual Basic code so that once the end of the row is reached, Excel moves to the beginning of the next row • After the Do Loop tell Excel to ActiveCell.Offset(1,-4).Select • Then set up another Do Loop so that Excel keeps doing this until the whole table has been evaluated
Once the first Do Loop is finished it moves to the next row and keeps going until the next row is empty
Advice • Writing programs requires trial and error • Use the macro recorder to get most of the code • Then edit this code to make it do exactly what you want • Download a copy of all these notes (www.qubexcel.co.uk) and refer back to them when you have a particular task to perform • The only way to get really confident with Excel and VBA is to use them regularly