How to Calculate Multiples Using a While Loop
Loops are the gist of computer programming because they allow programmers to automate tasks. For example, if you want the computer to write the numbers 1 through 1000, you set a counter to 1, program a loop, write the number, change cells, add 1 to the counter, go back to the first statement in the loop, and repeat through 1000. Loops have many forms, one of which is the “While” form. This statement tells the computer to do the commands between the “While” command and the “Loop” statement until the condition in the “While” command is reached. You might use a loop to calculate multiples.
Instructions
-
Cacluating Multiples with a While Loop
-
1
From a new worksheet, press “Alt” + “F11” to edit a Visual Basic program. Select “Insert” and “Module.”
-
2
Type the following code into the new module:
Sub Macro1()
'
'
'
'
'Comment: Calculate Multiples of Two Using a While Loop
'
Worksheets(“Sheet1”).ActivateX=1
Do While X<100
ActiveCell.Offset(0,1) = 2 * X
X = X + 1
ActiveCell.Offset(0,1).Activate
LoopEnd Sub
-
-
3
Run your program by hitting the “F5” key. Select the green “X” in the top left corner to review your results.
-
4
Confirm that the Visual Basic program has calculated multiples of 2 between 4 and 198 and placed them in successive columns.
-
5
Save the program if you wish by clicking “File” and “Save”. Give the file a name and press “Save.” Exit the spreadsheet by clicking “File” and “Exit.”
-
1