13
Microsoft Visual Basic 2010™ (Level 3) Contents Introduction ..............................................................................................................2 The Developer Tab ..................................................................................................2 Objects & Collections ............................................................................................2 Workbook and Worksheet Objects ..................................................2 Methods, Properties and Events ........................................................3 Absolute and Relative Referencing ...................................................................3 Variables and Arrays ...............................................................................................4 Defining Variable/Array Types ............................................................4 Variant Arrays ...........................................................................................5 Input/Output .............................................................................................................6 Output .........................................................................................................6 Input .............................................................................................................6 Loops ........................................................................................................................7 For … Next ..................................................................................................7 While … Wend .........................................................................................8 Do … Loop .................................................................................................8 Nested Loops ............................................................................................9 Conditional Statements ........................................................................................9 If … Then .....................................................................................................9 If … Then … Else .................................................................................... 10 GoTo .......................................................................................................... 10 File Input/Output .................................................................................................. 11 Opening and Closing Files ................................................................. 11 Input # ...................................................................................................... 11 Print # and Write # .............................................................................. 11 Help ..................................................................................................................... 12 Exercise ..................................................................................................................... 12 IT Training

Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

  • Upload
    ledat

  • View
    220

  • Download
    1

Embed Size (px)

Citation preview

Page 1: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

Microsoft Visual Basic 2010™ (Level 3)

Contents

Introduction ..............................................................................................................2

The Developer Tab ..................................................................................................2

Objects & Collections ............................................................................................2

Workbook and Worksheet Objects ..................................................2

Methods, Properties and Events ........................................................3

Absolute and Relative Referencing ...................................................................3

Variables and Arrays ...............................................................................................4

Defining Variable/Array Types ............................................................4

Variant Arrays ...........................................................................................5

Input/Output .............................................................................................................6

Output .........................................................................................................6

Input .............................................................................................................6

Loops ........................................................................................................................7

For … Next ..................................................................................................7

While … Wend .........................................................................................8

Do … Loop .................................................................................................8

Nested Loops ............................................................................................9

Conditional Statements ........................................................................................9

If … Then .....................................................................................................9

If … Then … Else .................................................................................... 10

GoTo .......................................................................................................... 10

File Input/Output .................................................................................................. 11

Opening and Closing Files ................................................................. 11

Input # ...................................................................................................... 11

Print # and Write # .............................................................................. 11

Help ..................................................................................................................... 12

Exercise ..................................................................................................................... 12

IT Training

Page 2: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

2

Introduction Visual Basic is the programming language used for writing macros. This document covers some of the commonly-used features of the language. If you are not already familiar with creating a macro in Excel, work through Microsoft Excel 2013: Macros before attempting these notes.

The Developer Tab Begin by opening the example file used in the course (this already has several macros, to save you writing the code yourself – as you'll see the code has to be very precisely written):

1. Load up Excel as usual then press <Ctrl o> (or use Open from the File tab)

2. Double click on My Computer then again on Data (D):, open the Training folder and then the file vba.xlsm

(if you are working on your own computer you can load the file by clicking on the link provided here)

Next, display the Developer tab on the Ribbon. There is a [Macros] button on the View tab, but it's easier to use the set of buttons on the Developer tab:

1. Move to the File tab and choose Options followed by Customize Ribbon

2. In the list on the right, turn on the Developer check box

3. Press <Enter> for [OK] to display the tab (and close the Excel Options dialog box)

Objects & Collections Before looking at the macros in the example file, it's important to understand the structure used in Visual Basic programming. The fundamental building blocks are called Objects. In Excel, the most-frequently used objects are Workbook, Worksheet, Sheet, and Range. While a Worksheet object only represents a worksheet, a Sheet can be any type of sheet (eg a chart sheet). A Range can refer to a single cell or range of cells. Other common objects include Charts and PivotTables. A Collection is a group of objects of the same class.

Workbook and Worksheet Objects A Workbook is an Excel file. The workbook collection contains all the Excel files currently open. Every workbook contains at least one Worksheet. The worksheet collection consists of all the worksheets in the workbook (excluding any chart sheet or macro sheet). In VBA, Workbook /Worksheets are always referenced in plural.

In VBA, a worksheet can be referenced directly (its name in quotes) or via a number index:

Worksheets(sheetname) - eg Worksheets("Sheet1") is the worksheet named "Sheet1"

Worksheets(number) – eg Worksheets(1) is the leftmost worksheet in the collection

Note that Worksheets(1) is not necessary the same sheet as Worksheets("Sheet1"). Sheets is a collection of worksheets, chart sheets and macro sheets (if present). A sheet can be indexed just like a worksheet. Sheets(1) is the leftmost sheet, no matter what sort of sheet it is. Note also that you can

use ActiveSheet to refer to a sheet (also ActiveSheet.Next and ActiveSheet.Previous).

To refer to sheets (or other objects) with the same name, you have to name it precisely. For example:

Workbooks("Book1").Worksheets("Sheet1")

Workbooks(2).Worksheets("Sheet1")

If the object is not named specifically, the active or the current object (ie workbook or worksheet) is used. The white sheet tab at the bottom of the spreadsheet shows which sheet is currently active.

Page 3: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

3

Methods, Properties and Events Each object can have its own methods, properties and events. A Method is an action performed on an object. A Property is a built-in (or user-defined) characteristic of the object. You can program an Event to occur when a workbook is created or opened, when another sheet is activated, or when a PivotTable is created. Events are rarely used by the average programmer and are not dealt with in this document.

Below are examples of some methods:

Workbooks.Close - closes the active workbook

ActiveSheet.Delete – to delete the active worksheet (the dialog box is displayed)

Worksheets("Sheet2").Delete – deletes Sheet2 (but doesn't change which sheet is active)

Worksheets("Sheet4").Copy – copies Sheet4 to a new workbook

ActiveSheet.Copy After="Sheet1" – copies active worksheet and places it after Sheet1

Sheets("Chart1").Activate – makes Chart1 the active sheet

Sheets("Chart2").PrintPreview – previews Chart2 (.PrintOut – prints out the chart)

Worksheets.Add – creates a new worksheet, which is then activated

Range("A1").Select – selects cell A1

Worksheets(1).Columns("A:B").AutoFit – autofits columns A and B on first sheet

ActiveSheet.Range("A1:D9").Sort – sorts A1 to D9 on active sheet using values in column A

And here are some examples of properties:

Worksheets.Count – tells you how many worksheets are currently open (ditto for Workbooks)

Range("A1").Value = 10 – puts a value of 10 in cell A1

Range("A1") = 10 – the default property for a Range is Value, so this can be omitted

Selection.Value = "Profit" – puts the Word Profit in the active cell (Value can be omitted)

ActiveSheet.Name = "Results" – renames the active sheet as Results

Absolute and Relative Referencing There are two ways of referencing in VBA - absolute and relative. Firstly, absolute references:

Range("A1").Select – an absolute reference which makes cell A1 the active cell

Range("A2:A10") = Range("A1") * 10 – stores ten times A1’s value in cells A2 to A10

Cells(1,3) = "hello" – puts hello in cell C3; Cells(row,column) can also be used

Relative references can have two components. Firstly there's an offset which is denoted using the number of rows and columns away from the active cell. Only positive values are allowed.

ActiveCell.Offset(0, 1) = "x" – this puts an x in the cell to the right of the active cell

ActiveCell.Offset(1, 0).Select – this selects the cell below the current active cell

ActiveCell.Offset(0,1) = ActiveCell * 2 – puts twice the active cell in the cell to right

Secondly, you can also select a range relative to the offset. With this, Range("A1") denotes the offset cell, not the cell in the first row of the left column of the whole worksheet. Though confusing, you soon get used to it.

ActiveCell.Offset(3,0).Range("B1").Select – selects the cell in the column to the right

(column B), three rows down

Page 4: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

4

Now try out the first macro in the example file and see if you can understand what's happening at each stage:

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

2. Select Macro1 then click on [Edit]

This will take you into the Visual Basic Editor. Before running the macro, decrease the size of the VBE window so that you can see the Excel worksheet at the same time:

3. [Maximize] the inner code window, if necessary, and [Close] the two panes on the left

4. Using the mouse, point to the far left of the VBE window and drag it to the right so that it occupies only

half the screen (if the window is maximized, you'll need to click on [Restore Down] first)

5. Now run the macro by pressing <F8> - this steps through the lines one at a time (the arrow and yellow

highlight indicates where the macro has reached)

6. Repeat step 5 until the last statement (End Sub) is no longer highlighted

Make sure you understand the statements as they are performed. You can repeat the macro a second time by

pressing <F8> again, should you so wish.

Variables and Arrays Considerable use is made of variables and arrays in VBA programming. A variable can be thought of as equivalent to a cell on a worksheet in that it can store data (and that data can be replaced by new values, as can happen if you change the data in an Excel cell). An array is equivalent to a range of cells (a row, column or block) and is essentially a set of variables. Variables and arrays are given names, in the same way a cell or range of cells can be named (eg spaces are not allowed in a variable or array name).

Defining Variable/Array Types By default, any type of data can be held in a variable, so at one point it could hold a number and at another some text. This is not recommended, however, and the type of variable should be declared explicitly. A variable or array can be restricted to hold certain kinds of data in a similar way to a Format (eg Date or Text) being applied to a cell. This is done through a DIM statement (a single quote introduces a comment):

Dim x As String ' variable x is for text

Dim A2 As String ' variable names can include a number

Dim i, j As Integer ' variables i and j are for whole numbers

Dim birthday As Date ' variable birthday is for a date

Dim y As Double ' variable y is for double-precision numbers

Dim xx as variant ' any sort of data can be held in variable xx

Note: An older notation was to define an integer or string using a % or $ sign (respectively) attached to the variable name. Thus, if the number 12.4 was stored in a variable w%, it would be stored as 12. This notation can still be used but such variables cannot be defined using DIM (ie Dim x$ as String gives an error).

Arrays are a simple way to define a series of variables using a single name. When defining an array, the number of items which form the array should be declared. These are known as the array bounds. Arrays can be one-dimensional (similar to a row or column of cells) or two-dimensional (like a block of cells). You can in fact have even more dimensions!

Dim x(10) as String ' defines 10 variables called x(1), x(2),

x(3) ... x(10) for storing text

Dim m(2,2) as Single ' defines 4 variables called m(1,1),

m(1,2), m(2,1) and m(2,2) for numbers

Dim z(5 to 9) as Date ' defines 5 variables z(5), z(6) ... z(9)

for storing dates

Page 5: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

5

Note: By default, array bounds start at zero. Thus, in the first example above, there is also an x(0). In the second example, there are 5 extra elements – m(0,0), m(0,1), m(0,2), m(1,0) and m(2,0). The explicit declaration in the third example, however, means that only these elements exist. You don't have to use these extra elements if you don't want to and you can define a lower bound of 1 using an Option Base 1

statement at the very top of your VBA code (this sets the default for all the macros in that file).

Variant Arrays Often, the data held in a row, column or block of cells differs in type (text, numbers, dates etc) or the type may be unknown. When this is the case, a variant array can be defined:

Dim myrow(3) as Variant ' myrow is an array of 3 values

myrow(1) = 5 ' a number is stored in myrow(1)

myrow(2) = "Yes" ' text is stored in myrow(2)

myrow(3) = "31/Dec/1999" ' a date is stored in myrow(3)

The Array function can be used to supply data to a variant array. The example below first declares the variable as variant, then defines it as an array containing the specified values.

Dim players As Variant

players = Array("Ron", "Dan", "Fred", "Tim", "Chris", "Paul", _

"Jon", "Jamie", "Sam", "Pete")

MsgBox(players(3)) ' displays Tim – Ron is in players(0)

Note the underscore at the end of the second line in this example. This character is used to indicate that the statement continues onto a second line.

Let’s see how variables and arrays work by running Macro2.

1. The VBA window should still be displayed – if not, click on the [Macros] button and [Edit] Macro2

2. Click on Macro2 then use <F8> to step through the macro

This macro picks up the values from an array x which is declared as variant so that it can hold any data. The variable w can only hold whole numbers (it’s declared as integer). If a variable is used or declared within a macro, the value stored in it is only held while the macro is running. Try running Macro2 again:

3. Run the macro again, using <F8> (or <F5> if you just want to run it rather than step through it) – you should find nothing has changed – w has no value when the macro is started

You can, however, retain the value so that it can be used in other macros. To do this, you have to declare it outside the macros.

4. Add a single quote before the DIM w as Integer statement in the macro (to turn it into a comment )

5. Using the scroll bar, move to the very top of the VBA display and delete the single quote from the DIM

statement here, to activate it

6. Click anywhere within Macro2 and run it again (using <F8> or <F5>) – the cell is left empty as w has now been declared variant (it was set to 0 when declared an integer)

7. Repeat step 6 to run it a second time - this time A2 is set to 10

The value is held because w is declared in the DIM statement above the macros. If you run it a third time, its value becomes 20. Finally, try adding a statement which gets rid of the zeroth element of the array:

8. Uncomment the statement Option Base 1 at the very top of the VBA pane – above the DIM

9. Click on Macro2 then press <F5> to run it

You should find the word data appears in cell A2; an error message also appears:

10. Press <Enter> for [Debug] then correct the statement to read ActiveSheet.Name = x(1)

11. Press <F8> or <F5> to complete the macro

Page 6: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

6

Input/Output Sometimes, when running a macro, a user needs to interact with the program - either to supply some data or be told some information. The latter is often used when developing a macro, to test whether the code is running correctly. The following sections deal with what is known as Input and Output.

Output The code needed to get information from a macro is the Msgbox statement. This can be used either to relay a fixed message (eg that the macro has reached a particular point in the code) or to give the current value of a variable used in the program or data held in a cell. When a Msgbox statement is run, a dialog box appears on the screen, which must be OK'd by the user. Note that Msgbox requires a string argument – non-strings can easily be converted using the Cstr function. Below are some examples:

Msgbox("Here") or Msgbox "Here" ' the macro has reached this point

Msgbox(A) ' displays what’s held in string A

Msgbox(Cstr(x)) ' displays the number held in x

Msgbox("x = " & Cstr(x)) ' as above but adds x =

Msgbox(Cstr(Range("C2"))) ' displays the value held in cell C2

Msgbox ActiveSheet.Name ' displays the active sheet's name

The default dialog box simply has an [OK] button but further buttons can be added by including a prompt parameter after the message. Prompt value 4, for example, gives [Yes] and [No] buttons. The macro can then detect which response has been chosen and can act accordingly. The example below both displays the dialog box and acts on the result. See Visual Basic online help for full details.

If MsgBox("Continue?",4) = vbNo Then End 'see IF later

Input To supply information to a macro, an Inputbox statement is used. This could take the form of a reply to a question or to supply a data value. The information will then be passed to the macro via a variable, which can then be used to determine what happens next. Again, a dialogue box is displayed to which the user must respond.

Range("C1") = Inputbox("Input value for cell C1")

Q = Inputbox("Do you want to continue (Yes or No)?")

If Q = "No" Then End 'see IF later in these notes

x = Inputbox("How many rows of data are there?")

For i = 1 to x 'see LOOPS later in these notes

The first example supplies a value to a particular cell while the other two examples supply values for later use in the macro, as indicated by the indented comments which follows.

Macro3 has some input/output statements:

1. Click inside Macro3 then use <F8> to run through it

2. Press <F5> (or use <F8> again) if you want to try it a second time

Page 7: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

7

Loops By using loops, macros can process a lot of data in Excel. These are set up around other instructions to carry them out a set number of times or until a particular condition is reached. There are three main statement pairs which are used to create loops; each has one statement marking the start of the loop and the other its end. These are: For … Next, While … Wend and Do … Loop

For … Next Perhaps the simplest pair of statements is For … Next. The For statement sets up a variable which increases in value by 1 each time the loop is completed. The Next statement marks the end of the loop, sending the macro back to the For statement. This statement also checks whether the loop has exceeded its final value and, if it has, passes control to the statement following the Next statement.

Normally, the loop variable starts with a value of 1 but this needn't be the case (for example, you may want the macro to work from a particular row on a worksheet). The increase value (step value) is also usually 1 but needn't be; indeed negative or fractional steps can also be used. Here are some examples:

For i = 1 to 10 ' this example sets the

Cells(i,1) = i ' values in cells A1 to A10

Next i ' equal to 1, 2, ... 9, 10

For j = 5 to 8 ' this example sets the

Range("A"&CStr(j)) = j*j ' values in cells A5 to A8

Next j ' equal to 25, 36, 49 & 64

For k = 0 to 9 step 2 ' this example sets cell

Range("A"&CStr(k+1)) = k ' A1 to 0, A3 to 2, A5 to 4

Next k ' A7 to 6 and A9 to 8

For m = 10 to 1 step -1 ' this picks up data from

Cells(11-m,1) = Cells(m,2) ' column B, starting in B10

Next m ' so A1 = B10, A2 = B9 etc

For Each y In Range(“A1:A5”) ' this uses the values

Cells(y,2) = y ' stored in cells A1 to A5

Next y ' to set the values for y

To jump out of a loop at any time, use an Exit For statement:

For i = 1 To 100 ' the loop ends when a # is

x = InputBox("Enter data") ' entered as data

If x = "#" Then Exit For Else Cells(i, 1) = x

Next i

Msgbox CStr(i-1) & " rows of data" ' says how many rows entered

A more complicated form of For… Next is the For Each … Next statement. This can be used to pick up loop values from a cell range, or to repeat a loop for each member of an array or each object in a collection (for example, each cell in a range). Visual Basic can automatically set up a counter for the loop if none is specified:

Page 8: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

8

For Each y In Range("A1:A5") ' this uses the values

Cells(y,2) = y ' stored in cells A1 to A5

Next y ' to set the values for y

Dim Test(10) as Array ' Test is an array of 10.

For Each i in Test ' this example stores the

Test(i) = Range("A"&CStr(i)) ' contents of cells A1 to

Next i ' A10 in the array

Dim x as Range ' x is defined as a Range.

For Each x in Range("A1:A10") ' the example works through

x.ClearFormats ' the cells A1 to A10

x = 0 ' clearing any formatting

Next x ' then setting them to 0

While … Wend An alternative form of looping is provided by the While statement. An examples is given below.

While i < 10 ' this example runs until

X = Selection ' it finds 10 # in a column

If X = "#" then i = i + 1

ActiveCell.Offset(1, 0).Range("a1").Select

Wend

Do … Loop Yet another way of looping is provided by the Do statement:

Do Until j = 999 ' this example runs down a

ActiveCell.Offset(1, 0).Range("a1").Select

j = Selection ' column until it finds a

Loop ' value of 999

Do While j <> 999 ' could also be used

An alternative form uses a While or Until statement to mark the end of the loop:

Do

ActiveCell.Offset(1, 0).Range("a1").Select

j = Selection ' here while marks the

While j < 999 ' end of the loop

Until j = 999 ' could also be used

Macro4 contains examples of all the different types of loops – try running it next:

1. Click inside Macro4 then use <F8> to run through it

2. Using the mouse, position the cursor over any variable (loop counter) to see its current value

Page 9: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

9

Nested Loops One loop can be placed inside another. In Excel, one loop can be used to control the columns, the other the

rows. In the second example below, the first loop determines which worksheet is used.

For i = 1 to 10 ' Cells A1 to B5 are filled

For j = 1 to 5 ' with values from 1 to 5

Cells(i, j) = i*j ' then row 2 with 2, 4, 6,

Next j ' 8, 10 down to row 10 with

Next i ' 10, 20, 30, 40, 50

Dim Sht as Worksheet ' This example works

For Each Sht in Worksheets ' through the data on each

Do Until j = 999 ' worksheet in a file until

' statements to be looped ' an end-of-data value of

Loop ' 999 is found then moves

Next Sht ' on to the next sheet

Macro5 shows an example of a nested loop:

1. Click inside Macro5 then use <F8> to step through it

Note how the inner (j) loop is executed each time the outer (i) loop is run – again, you can use the mouse to check the progress by looking at the values held in i and j.

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 set alternative routes through the macro

If … Then The simplest conditional statement performs a single action if the test is true:

If Selection < 1 Then Selection = 0

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

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

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

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

If Not Selection >=0 Then Selection = 0 ' -ve values set to 0

If A = "yes" Or A = "y" Then ... 'answer can be y or yes

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

Page 10: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

10

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 isn't true:

If ActiveCell = "" Then ActiveCell = 0 _ ' sets an empty cell

Else ActiveCell.Offset(1,0).Select ' to 0 or moves down

If ActiveCell = "" Or ActiveCell = " " _ ' this checks for an

Then ActiveCell = 0 _ ' empty cell or one

Else ActiveCell.Offset(1,0).Select ' with a space

Several statements can be included within a conditional:

If Q = "Yes" Then

' Type in your statements here

ElseIf Q = "No" Then

' Type in your statements here

Else

' Type in your statements here

End If

Macro6 includes some conditional statements:

1. Click inside Macro6 then use <F8> to step through it, typing a value less than 1 or greater than 10 when

asked - the macro will end prematurely

2. Rerun the macro (press <F8>) but type in a valid value

A somewhat obscure form of the IF statement is #IF. This can be used to create a macro which will perform different code according to the operating system:

#If Win32 Then

' Place 32-bit Windows statements here

#ElseIf Win64 Then

'. Place 64-bit Windows statements here

#Else

'. Place Mac statements here

#End If

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. Using GoTo is considered by purists to be a lazy way of programming as the macro statements can usually be rewritten to produce the same result. :

question: Selection = InputBox("What percentage is a half?")

If Selection <> 50 Then ' This tests to see whether

Msgbox("Wrong, try again") ' a question has been

GoTo question ' answered correctly and

Else MsgBox ("Correct") ' asks it again if the

EndIf ' answer was wrong

Page 11: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

11

Macro6 was annoying in that you didn't get a second chance if you typed in a number which was out-of-range. To get over this problem, activate the GoTo statement:

1. Edit Macro6 to remove the single quote comment before the statement GoTo again

2. Press <F8> to step through the macro and again type in a value less than 1 or greater than 10

3. Now you are given a second chance – type in a valid number then press <F5> to run the macro to

completion

File Input/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 relevant 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 "data1.txt" For Input As #1 ' Open file data1.txt for input

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

Open "keep.xls" For Append As #2 ' Add more data to keep.xls

Note: A file can also be opened for both input and output simultaneously using For Random – see the online Help provided by Microsoft for further details.

Files should be closed using a Close # statement once you have finished using them:

Close #1 ' Closes the file opened as #1

Input # An Input # statement is used to get data from a file which has previously been opened. Note the EOF function, which can usefully be used to detect the end of the file:

Do While Not EOF(2) ' Loop until end of file on #2

Input #2, a, b, c ' Read data into 3 variables

Loop

Close #2 ' Close 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.

Line Input #2, xxx ' Read data into variable xxx

Print # and Write #

Page 12: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

12

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 #3, "Output Results" ' Prints specified text to file

Print #3, ' Print a blank line

Print #3, "x" ; Spc(5) ; "y" ' Separate strings with 5 spaces

Print #3, x; Tab ; y ' Separate x and y by a tab

Print #1, Tab(6) ; "End" ' Print End at column 6

Write #1, x, y, z ' Separates x, y, z by commas

Write #1, ' Writes out a blank line

Write #1, "End of data" ' Outputs "End of data" in quotes

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

1. Click inside Macro7 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.

Help Microsoft provides extensive (if sometimes incomprehensible) help on VBA. For example, to see the list of possible methods/properties for an object:

1. Press click on the [Help] button (the question mark) in the VBA editor (or press <F1>)

2. In the Search here box type the required keywords – eg worksheet object

3. To see the possible methods/properties, click on Worksheet Object Members

4. Select a Method (eg Activate) and note the example at the foot of the help page

5. End by closing the Help system

It's also worth using a search engine (such as Google) to get examples of VBA programming from elsewhere on the web.

Exercise Macro8 is currently empty. Try writing your own macro following what you have learnt. You can, if you want, follow 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.

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 (the Range statement)

2. Fill that cell with a value

3. Store the value in a variable (call it x)

4. Move to the top of an empty column

5. Set up a loop to fill the column with x occurrences of your name

6. Fit the column width to the text (Autofit)

Page 13: Microsoft Visual Basic 2010 - University of Reading · PDF fileMicrosoft Visual Basic 2010™ ... work through Microsoft Excel 2013: ... This will take you into the Visual Basic Editor

13

7. Get the macro to ask whether you would like to run again

8. Set up a statement which will go back to the start if you answer Yes

™ Trademark owned by Microsoft Corporation. © Screen shot(s) reprinted by permission from Microsoft Corporation. Copyright © 2012: The University of Reading Last Revised: May 2012