0% found this document useful (0 votes)
2 views

Lecture 20 - Visual Basic

The document provides instructions for creating and manipulating macros in Microsoft Visual Basic, including saving files, using nested loops, conditional statements, and file input/output operations. It explains how to structure macros with examples and encourages users to practice by writing their own macros. Additionally, it outlines steps for completing an assignment related to these concepts.

Uploaded by

derpydiane101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Lecture 20 - Visual Basic

The document provides instructions for creating and manipulating macros in Microsoft Visual Basic, including saving files, using nested loops, conditional statements, and file input/output operations. It explains how to structure macros with examples and encourages users to practice by writing their own macros. Additionally, it outlines steps for completing an assignment related to these concepts.

Uploaded by

derpydiane101
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Microsoft Visual Basic – continued

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.

Nested Loop examples:

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.

Dim Sht as Worksheet


For Each Sht in Worksheets
Do Until j = 999
Loop
Next Sht
This moves through each worksheet in the file until an end-of-data value of 999 is
located, then moves to the next worksheet.

MacroE shows an example of a nested loop.

1. On the Developer tab, click on the [Macros] button


2. Select MacroE then click on [Edit]
3. Click inside MacroE then use [F8] to step through it.

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:

If Selection < 1 Then Selection = 0


This looks at the current selection value and sets it to zero if it is less than 1. Applies if
it is negative, right?

If Selection = "" Then ActiveCell.Offset(0, 1) = "missing data"


This checks if a cell is blank, then puts ‘missing data’ in the cell zero rows and one
column away.

If Selection = "" Then Selection = InputBox("Enter a value")


This checks if a cell is blank, then shows an Input Box requesting a value be entered.

If Sheet.Name <> "Sheet1" then MsgBox("Start Macro from Sheet1")


This checks the name of the current worksheet, and if it is not Sheet1, gives the user a
message box informing the user that the macro needs to be started from Sheet1.

Tests can then be made more complex by the use of And, Or or Not:

If Not Selection >=0 Then Selection = 0


This sets negative values to 0.

If A = "yes" Or A = "y" Then ...


This indicates that an answer can be yes or just y.

If A = "y" And Selection = 0 Then Inputbox("Input new value")


This says that if A is y and the selection is also 0, then show the user an input box
requesting entry of a new value.
If … Then … Else
A more complex form of the If statement is If … Then … Else.
This lets you set up an alternative action or set of statements if the conditional test is not true.

If ActiveCell = "" Then ActiveCell = 0


Else ActiveCell.Offset(1,0).Select
This sets an empty cell to 0 or moves one row and zero columns if the cell is not empty.

If ActiveCell = "" Or ActiveCell = " "


Then ActiveCell = 0
Else ActiveCell.Offset(1,0).Select
This sets an empty cell or a cell containing just a space to 0 or moves one row and zero
columns if the cell is not empty or does not contain just a space.

Several statements can be included within a conditional:

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.

MacroF includes some conditional statements:

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.

To rectify this problem, activate the GoTo statement:


6. Edit MacroF to remove the single quote comment before the statement GoTo again.
7. Press [F8] to step through the macro and again type in a value less than 1 or greater
than 10.
8. Now you are given a second chance – type in a valid number then press [F5] to run the
macro to completion.
To see how to use GoTo within an IF to rerun a macro based on a user-defined
answer, watch the second part of the Lecture 20 video – this can be extremely
helpful to you for completing the final section of this Lecture!

File Input and Output


Using a macro, you can open one or more files either to get data or write it out.
For example, you might want to process a series of files, picking up data from each and storing
that data in another file. The appropriate statements are covered below.

Opening and Closing Files


The Open statement is used to open a file. You have to state whether you want to use the file
for input or output when you open it.

Open File Examples:


Open "data1.txt" For Input As #1
This opens file data1.txt for input

Open "res-5.xls" For Output As #3


This opens res-5.xls for output

Open "keep.xls" For Append As #2


This adds (appends) more data to keep.xls

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).

Do While Not EOF(2)


Input #2, a, b, c
Loop
Close #2
This reads data into three variables and keeps looping and reading data into variables
until it reaches the end of the file (EOF) on #2 – then it closes the file.

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:

Line Input #2, xxx


This reads data into variable xxx

Print # and Write #


Two statements are provided for writing information to a file, Print # and Write #.
When using a Print # statement, it's up to the user to specify how the data is to be written.
A Write # statement automatically inserts commas between items and quotation marks around
strings as they are written to the file.

Print and Write examples:

Print #3, "Output Results"


This prints specified text to file

Print #3,
This prints a blank line

Print #3, "x" ; Spc(5) ; "y"


This separates strings with 5 spaces

Print #3, x; Tab ; y


This separates x and y by a tab

Print #1, Tab(6) ; "End"


This prints End at column 6

Write #1, x, y, z
This separates x, y, z by commas
Write #1,
This writes out a blank line

Write #1, "End of data"


This outputs "End of data" in quotes

MacroG covers an example of using other files both for input and output:

9. Click inside MacroG then use <F8> to step through it

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.

You might also like