Lecture 20 - Visual Basic
Lecture 20 - Visual Basic
Open the “Assignment 19.[Your Last Name].xlsm” file that you saved to your computer. Click on
the File tab, then choose Save As. Save the file to your computer as “Assignment 20.[Your Last
Name].xlsm”. We’re doing this now to avoid you accidentally saving over your Assignment 19
file if you haven’t yet submitted it.
To see how to record a blank macro and then edit it, watch the first part of the
Lecture 20 video.
Nested Loops
In Lecture 19 we discussed loops.
Now let’s visit the concept that one loop can be placed inside another. For example, one loop
can be used to control the columns, the other the rows.
For i = 1 to 10
For j = 1 to 5
Cells(i, j) = i*j
Next j
Next i
This fills cells A1 to E1 with values from 1 to 5; then A2 to E2 with the values 2, 4, 6, 8,
10; A3 to E3 with 3, 6, 9, 12, 15. Basically, it creates a multiplication table through row
10! The inner loop using variable j puts the values in the columns, then the next i
moves the code to the next row.
Note how the inner (j) loop is executed each time the outer (i) loop is run – you can use the
mouse to check the progress by looking at the values held in i and j.
This inner loop execution can be seen clearly if you copy the first nested loop example code
above and paste it into visual basic and step through it.
Conditional Statements
Conditional statements are used to carry out one or more instructions in a macro - only if a test
is true. They can be used to give alternative values or actions, or to set alternative routes
through the macro.
If … Then
The simplest conditional statement performs a single action if the test is true:
If…Then examples:
Tests can then be made more complex by the use of And, Or or Not:
If Q = "Yes" Then
' Type in your statements here for what you want to happen if Q is “Yes”
ElseIf Q = "No" Then
' Type in your statements here for what you want to happen if Q is “No”
Else
' Type in your statements here for what you want to happen if Q is a value other than
“Yes” or “No”.
End If
This checks Q. If it’s Yes, it does something. If it’s No, it does something, and if it is not
Yes or No, it does this other thing. Then it ends the If.
4. Click inside MacroF then use [F8] to step through it, typing a value less than 1 or
greater than 10 when asked - the macro will end prematurely.
5. Rerun the macro (press [F8]) but this time type in a valid value.
GoTo
A GoTo statement jumps to a named statement rather than to the next one in the macro.
The jump could be forwards or backwards.
question:
Selection = InputBox("What percentage is a half?")
If Selection <> 50 Then
Msgbox("Wrong, try again")
GoTo question
Else MsgBox ("Correct")
EndIf
This tests to see whether a question was answered correctly, and asks the question
again if the answer was wrong. The first line (question:) is where the code will return to
from the GoTo statement, then continues (reruns) from that point.
MacroF was annoying because you didn't get a second chance if you typed in a number which
was out-of-range.
Note** A file can be opened for both input and output simultaneously using For Random.
Files should be closed using a Close # statement once you have finished using them.
Close #1
This closes the file opened as #1
Input #
An Input # statement is used to get data from a file which has been opened previously.
Note the EOF function, which is used to detect the end of the file (EOF).
An alternative form of the Input # statement is Line Input #. This reads a whole line of text
at a time, which is stored in a single variable. Example:
Print #3,
This prints a blank line
Write #1, x, y, z
This separates x, y, z by commas
Write #1,
This writes out a blank line
MacroG covers an example of using other files both for input and output:
This is quite a complicated macro, so watch carefully what is happening at each stage.
Note that the macro creates a file called testing.txt and a new Excel file each time it runs, which
you may want to delete.
Your turn
MacroH is currently empty. Write your own macro following what you have learned. Use the
following instructions, which make use of the currently unused Sheet3. You'll find that as you
type an object you are prompted by VBA with the required syntax and possible
methods/properties/events. To speed up typing, you can use the arrow keys to move up and
down the lists to select the required property etc. then press [Ctrl-Enter] to add it to your
statement. Take writing out what you have to do one step at a time!
As you write your statements, it's worth checking each in turn to see whether it works properly
by running the macro. Note that if you step through the macro ([F8]) you can edit a statement
and then reset the next line to be run simply by dragging the yellow arrow up or down the VBA
statements.
1. Get the macro to move to a particular cell (use the Range statement)
2. Fill that cell with a value (use Selection)
3. Store the value in a variable (call it x)
4. Move to the top of an empty column (use ActiveCell.Offset)
5. Set up a loop to fill the column with x occurrences of your name (use For, Next and
Selection)
6. Fit the column width to the text (use Autofit)
7. Get the macro to ask whether you would like to run again (use MsgBox)
8. Set up a statement which will go back to the start if you answer Yes (this is where
watching the video can be very helpful)
Click on the File tab, then choose Save As. Save the file to your computer as “Assignment
20.[Your Last Name].xlsm”. In Canvas, upload your assignment document as the response to
Question 1 in the Lecture 20 assessment, then answer the rest of the assessment based on
your file and/or comprehension of the lecture.