Knocking Your Code for a Loop. Microsoft Excel VBA Programming
Reklama
Reklama
Chapter 10: Controlling Program Flow and Making Decisions
151
If you’ve ever wondered why I indent the code I present here, the previous listing serves as a good example. The indentations really help to make the nesting levels clear (at least I think so). If you don’t believe me, take a look at the same procedure without any indentation:
Sub CheckCell()
Dim Msg As String
Select Case IsEmpty(ActiveCell)
Case True
Msg = “is blank.”
Case Else
Select Case ActiveCell.HasFormula
Case True
Msg = “has a formula”
Case False
Select Case IsNumeric(ActiveCell)
Case True
Msg = “has a number”
Case Else
Msg = “has text”
End Select
End Select
End Select
MsgBox “Cell “ & ActiveCell.Address & “ “ & Msg
End Sub
Fairly incomprehensible, eh?
Knocking Your Code for a Loop
The term looping refers to repeating a block of VBA statements numerous times. In this section, I explain about several different types of loops.
There are two types of loops: good loops and bad loops. (Good loops get rewarded, and bad loops get sent to their room.)
The following code demonstrates a bad loop. The procedure simply enters consecutive numbers into a range. It starts by prompting the user for two values: a starting value and the total number of cells to fill. (Because
InputBox returns a string, I convert the strings to integers by using the
CInt function.) This loop uses the GoTo statement to control the flow. The
CellCount variable keeps track of how many cells are filled. If this value is less than the number requested by the user, program control loops back to
DoAnother.
Stáhnout
Reklama