Excel Laboratory Worksheet

advertisement
Excel
Laboratory
Worksheet
"Excel for non-users" section
Never used Excel? Then you start here. Even if you have used it before, review this section - you never know you might
learn something. This laboratory sheet will cover many features of Excel, all of which we will return to in greater detail
in the following laboratory sessions.
The laboratory sheet is written in instructions assuming you are running under the Windows operating system.
Firstly review the lecture on Excel. From your computer, launch Excel via a desktop icon or find the application on your
hard drive. You may be presented with an array of unnecessary gloss, just pick a new basic workbook. Usually by
default, the workbook will contain 3 worksheets, each accessed by the tabs at the bottom of the workbook. Let's set this
workbook up to meet our needs. We only need one worksheet. Delete the other two by clicking on each tab and pulling
down the Edit menu (choose the option you need) – there is a right mouse button click on the tab that is an alternative
deletion mechanism.
The worksheet will be a company payroll. Name the worksheet payroll by double clicking the tab, and typing in the
name. Save the workbook (File menu) with your company's name. Spreadsheets work in a very simple fashion. You will
work in a cell or several cells, each cell being the intersection of a row and column. You select the cell(s) with the mouse
pointer and by clicking. The chosen cell is now active and you can begin entering data or commands. Select a cell and
note how the interface changes to make you aware of your selection. Use the arrow keys to quickly navigate between
adjacent cells. Use the scroll bars to navigate over larger distances on the worksheet.
Select a group of cells by clicking on cell B3, and while holding down the button, drag it down to B32. Now you have a
range of cells selected. This process can work up, right and left also. Another way is to click on B3 and then click on
B32 while holding down the shift key. The same effect. While still holding down the shift key, click G10.
Entering data
Starting in cell A1 begin entering the following data. It is payroll data consisting of an employee ID, name, age, pay rate
and hours of work. Those five categories make good column headings so insert them first. The data is,
00860,K.
00123,F.
00149,T.
00066,J.
00160,B.
Jay,52,16.65,95
Parr,21,7.50,180
Fredricks,42,11.35,235
Johnson-Smythe-Brown,55,18.90,250
Honors,18,6.65,42
A “text” file called payroll.txt is already available to you with this data inserted. Open this file within Excel
(restricting the eligible files to Text Files) and follow the instructions of the import wizard. A new workbook with the
data properly formatted will appear. Select all the data and copy. Go to your payroll worksheet select the cell A2 and
then paste. All the cells will appear in their appropriate place. Close down the "temporary workbook" created by the
wizard. Now select any cell containing data, and notice the entry box has a copy of the contents of the cell. If you wish to
edit this cell you click in this entry box and do your editing there.
1/8
Calculating values
With the raw data in place, what are some of the important numbers needing calculation? Clearly each individual's
monthly pay is necessary. K. Jay's monthly pay should be $1581.75, but this needs to be added as a formula. In cell F2
type =d2*e2 and then press return. Cell F2 will now appear to have the value 1581.75, but it really still has the formula
in place. For instance select F2, and look at the entry box. Select E2 and type 100. Note that F2 is automatically updated.
Now select UnDo from the Edit menu. Formula dependencies are highlighted by selecting F2, then placing the cursor in
the entry box. Notice the highlighting that occurs.
Replicating
Now I have one formula in place what about the rest? You don't want to type them all, simply select the range of cells
(see above) from F2 to F6. Then from the Edit menu select Fill->Down. Now all the correct formulae are all in place.
Select cell F6 and its contents should read =d6*e6. The filling option takes care of the cell referencing for you where it
can. There is a short cut to this fill down menu. Select F6 and place the cursor on the bottom right hand corner of the
active cell (the cursor will change shape). Click and drag while holding the mouse button down. Release when you have
covered the selection F2 to F6.
Entering functions
As far as the company is concerned the monthly total pay is important. In other words the sum of the numbers in F2 to
F6. Select F8 and type =sum(f2:f6) and hit return.
Another way to do this is to type =sum( then select the range F2 to F6 with the mouse and Excel will automatically type
in the range. Then type ) and hit return.
Charting
While holding down the Command key select B2:B6 and then select F2:F6. Both should be highlighted. Choose the
Chart Wizard from the toolbars. Select a pie chart and then follow the wizard's selections to create a breakdown chart of
the payrolls.
Now let’s build a spreadsheet application
You are contacted by a university physics lecturer who wishes you to design and implement a single workbook that will
help her check the results of her students' experiments which form part of their first year physics programme.
The experiment is "Newton's Rings" and by measuring various data the students will be able to determine the wavelength
of the light source used in the experiment. The student will typically do their analysis by hand, but the lecturer cannot
check each individual's workings because there are 500 of them. However they must hand in the data they measure as a
text file, and the lecturer wants to use this data as input to your spreadsheet to automatically generate the results. The
experimental set up is briefly described at the end of this description, but the detail is not relevant to the design of this
spreadsheet.
The experiments the students complete is governed by the equation
r = m"R
2/8
!
The students know the value of the constant R (in mm) in their experiment, and they will measure for various values of
the independent variable m, the value of the dependent variable r (in mm). Hence given the above equation they can
calculate an estimate of λ.
The physics lecturer informs you that her students will be provide their experimental data in the form of comma
delimited text as shown below,
1030
1,0.74
2,1.08
3,1.31
4,1.53
5,1.73
9,2.29
16,3.09
25,3.88
36,4.66
<- the value of R they used
<- the first value of m and its corresponding r (separated by a comma)
<- the second value of m and its corresponding r (separated by a comma)
...
The students are free to choose any one of several lens (hence R may differ from student group to student group). The
students may choose from one of two different light sources of unknown (to them) wavelength. The students are free to
sample their data over the values of m they wish, but the experimental equipment will at most allow for m=128.
Given a data file like the above your spreadsheet must determine the value of the wavelength λ of the light source used.
This can be done in a number of ways. The most basic analysis is to determine λ for every point in the data set. The
result would be
m
r
r2
lcalc=r2/(m*R)
1
2
3
…
36
0.74
1.08
1.31
…
4.66
0.5476
1.1664
1.7161
…
21.7156
531.65
566.21
555.37
…
585.64
You can see that because of experimental error each individual estimate of λ may vary dramatically. It would be better to
minimise the experimental errors by taking the average and this would result in λ=568.66nm. This differs from the actual
answer by about a 3.6%. Not a bad method but physicists (bless their souls) are pedantic and they know there is a better
to do this.
Note from the formula above, that if the square is taken then the relationship is r2=λRm, which is linear and the slope of
this line is λR. One can plot (simply for visual verification) the data set (r2 on the ordinate axis and m on the abscissa),
and also determine the "best" line that fits through the data using a linear regression. The slope of this line can be used to
determine λ . If one uses this method on the data above you get and answer with 0.3% error (a dramatic improvement!).
Your mission is to implement a spreadsheet in Excel which will perform this last method of calculation for λ .
Fortunately Excel can do it ALL for you, plotting, least squares regression etc. You can expect data in the form
described above, a comma delimited text file, with the value of R on the first line, followed by pairs of m and r on
subsequent lines. The file may consist of anything up to 128 data points.
There are several things you should consider,
•
It will be easier for your user if you set your spreadsheet up to accept data in the same way as it is laid
out in the data file. That is, A1 holds R, then A2 and B2 hold the first m and r respectively, etc.
3/8
•
•
•
•
•
The input must allow up to 128 data points, so define your plots, least squares regression etc on data
over this range, eg. A2:A129 etc. It won't matter if many of these cells are empty of data because it
doesn't affect the plot or the regression - functions based on cell ranges automatically account for empty
cells!
you must provide the appropriate plot for verification
the linear regression functions you need to consider are SLOPE() and INTERCEPT().
use array names (named cell range references) where possible.
can you make your empty spreadsheet (prior to when data is added) not have #REF! or #VALUE! etc
errors. Note my sample solution spreadsheet (the link below) doesn't, but you can do it if you consider
using IF().
Here are some additional test datasets to use from the website,
•
•
•
Sodium-full.txt.
Mercury-small.txt.
Mercury-full.txt.
You can check your solutions against an example solution spreadsheet available on the website. Search the web for the
wavelengths of Fraunhofer lamp lines and see if you can confirm the types of lamp being used.
Newton's Rings
A biconvex lens of known radius of curvature is placed on an optically flat
glass sheet. When illuminated with a light source of wavelength λ and viewed
from above, a series of concentric, alternating dark and bright rings can be
seen. These rings are interference fringes that arise from the variable thickness
air film between the base of the lens and the glass sheet. By using a travelling
microscope one can accurately measure the radius of each dark ring. If the
radius r of the Newton ring is much less than the radius of curvature R of the
lens, and if one discounts the presents of an air gap between the lens and the
flat plate then it can be shown that,
r = m"R
where m is the index of the interference ring (m=0, 1, 2 ...). Since for each m,
we can measure r, and the radius of curvature R is known, we can see that from
the above we can determine estimates of λ.
For those interested, the details of this phenomenon can be i found in any
elementary first year physics text in the Physical Sciences library.
!
Writing a simple VBA macro
We will use Excel's macro recording facility to enhance the above spreadsheet.
In order to use that spreadsheet you have to open a comma delimited text file in Excel, copy the contents, and then paste
that data into the second sheet of the solution spreadsheet. Once this is done the worksheet functions perform their
calculations. Clearly a useful improvement on this is if the user doesn't have to perform the arduous tasks of opening text
files, selecting, copying and pasting.
4/8
Recording a macro
You will implement this improvement in the following way.
1.
2.
3.
4.
5.
6.
7.
8.
9.
Use your solution workbook to the above.
Download all the text data files, and save them with their default names.
Launch the solution workbook. From the menus select Record New Macro. Give the macro a name and a
shortcut key if you wish. Begin recording.
Open the "LampB-small.txt" file, and follow the instructions of the import wizard, making sure you set the
delimiter to a comma, and open the data file.
The import wizard will launch another Excel workbook containing the data you have just imported. Select
the data set, and copy it.
Return to the solution workbook (under the Window menu) and then select the worksheet named
"Solution". Select cell A1 on that worksheet and paste the data.
Return to the workbook holding the data you imported (again through the Window menu), and close it. If
the ClipBoard Save Dialog Box comes up, just say no to saving the clipboard contents (at this stage you
have done the pasting and don't need it anymore).
Press the Stop Recording button.
Save (but don't quit) this solution workbook.
You have written a VBA program, though we can't see that yet. On the "Solution" worksheet Clear the contents of
columns A and B. Save again. You now have a blank Excel workbook (containing no data).
To run your program, use the short cut key (Command+Option+TheKeyYouChose), or from the menu select (Tools>Macro->Macros...) and click on Run. Now you have the data from "Mercury-small.txt" inserted in the correct place.
Select the worksheet called "CoverSheet" and type Command+=, (press = while holding down the Command key).
This latter operation is done because the Workbook has been set to Manual calculation rather than Automatic.
The macro code
Now let's look at the code
1.
2.
3.
In the solution workbook select the menu Tools->Macro->Visual Basic Editor. The menu bar and toolbar
will change but you may not see anything else. On this new menu bar select View->Project Explorer.
This will bring up a window with an outline of the project. Select "Module 1" in this window with the
mouse, and then make the menu selection View->Code. The Code Window that appears will contain the
recorded macro.
The code may seem very convoluted, but it mimics what you did. It essentially
•
•
•
•
•
opens the text file (with Workbooks.OpenText)
selects the data from the text file and copies it with Range().Select and Selection.Copy
returns you back to the main workbook, and to the "Solution" worksheet (with
Windows("YourFile").Activate and Sheets("Solution:).Select [the exact form depends on the
order in which you did things]).
selects the first cell to paste into (Range(A1).Select and ActiveSheet.Paste).
then it returns you to the data workbook and closes it (Windows("LampB-small.txt").Activate
and ActiveWorkbook().Close).
The specifics of the code aren't too important at this stage. However the code will only open the file you originally
specified, will only select the range of data you originally specified and when it closes the data workbook it uses the
original name.
If we want to generalise this macro to work with any file name, and with a different data range, what can we do?
5/8
Generalising the VBA
1.
We want the user to be able to specify the data file name. Obviously Excel/VBA will give you an object to do
this, we will just use it. It is a method that displays a File Open Dialog Box, that allows the user to choose a file
and this method returns back the name of the selected file. This is, the code that is necessary (we insert this
before the statement that begins with Workbooks.OpenText ....),
fname = Application.GetOpenFilename("Text Files (*.txt), *.txt")
Note: I am using a variable identifier (fname) to hold the file name chosen by the user. It is an undeclared
identifier for now. The name of the method that launches the File Dialog Box is Application.GetOpenFilename.
The argument "Text Files (*.txt), *.txt" restricts the File Dialog Box to showing ONLY text files.
2.
Since fname holds the name of the file to be opened we need to pass this name to the method that opens the
text file for us. That is
Workbooks.OpenText FileName:="....LampB-small.txt" etc is replaced with
FileName:= fname etc
Workbooks.OpenText
Now we can open any comma delimited text file.
3.
The range of data we select will vary from data file to data file. But we know there is a maximum number of
data items the workbook will accept, ie. 128 data points. So if we ALWAYS select the range A1:B129, we
will always get all of the data that is allowable.
Range("A1:B129").Select
Make these changes to your code and run the macro on all your data sets.
Making it right
The changed macro should work up to a point, ie. it won't let you close the workbook into which you imported the data.
Why? Because the Window().Activate method explicitly has the original window name "Mercurysmall.txt" as an argument. The name of the window we want to activate is the one currently opened to import the
text data. How is this solved?
The current active workbook's name is a property and can be obtained by ActiveWorkbook.Name. We use the same
idea as for the file name using fname. that is we will use a variable identifier wname (again undeclared), in which I will
store the window name of the workbook that holds the imported data.
Range("A1:B129").Select Selection.Copy
wname = ActiveWorkbook.Name
later in the code where we return to this workbook to close it we replace
Windows("LampB-small.txt").Activate
with
Windows(wname).Activate
You should now have a completely general macro to load data into this Workbook. Test it on all the data sets.
6/8
Declaring your variables
I have said it is good practice to always declare the variables you use. We haven't done this, ... yet. In your macro, the
first programming statements after the comments should be
Dim fname As String
Dim wname As String
Improving the interface
We developed some macros that opens user specified data files and as things go, this is an improvement. However the
user still has to know that there exist macros that must be launched manually, either through a menu or through a
shortcut key. The obvious next level of improvement is to provide buttons which when clicked will perform all the
necessary functions.
Click on the first worksheet of your spreadsheet. We are now going to add Buttons to the spreadsheet. Make the menu
selection View->Toolbars->Forms. The toolbar that appears contains a list of available controls and these controls are
just special drawing objects that can perform an action when they are clicked on.
1.
2.
3.
The control we want is a command button and this is selected by clicking on the "button" object in the
Forms Toolbar. Search through the available controls, you will eventually find it. As you move the mouse over
the controls its name will appear in a yellow box.
Once you have clicked the command button you can place it on the worksheet by dragging it across. Excel will
immediately ask you which macro you wish assigned to this button click. Choose "New". You will now find
yourself in the Visual Basic Editor. Simply return back to Excel.
You will find the button has white stubs around it allowing it to be resized and moved. By default this button
will be called Button 1. Resize and move the button to your desired location. Click on the text in the button
and type Import Data. Once you click off the button you will not be able to change it.
Now we have created a button but have not attached any code to it when it is clicked. On to the next exercise.
Improving the functionality
Now let's create some functionality for this button with some code
1.
2.
3.
4.
In your spreadsheet make the menu selection Tools->Macro->Visual Basic Editor. The menu bar and toolbar
will change but you may not see anything else. On this new menu bar select View->Project Explorer.
This will bring up a window with an outline of the project. Select "Module1" in this window with the mouse,
and then make the menu selection View->Code. The Code Window that appears will contain the macro you
ported from the Newton's Rings spreadsheet.
Returning to the Project Explorer select "Module2". Again View->Code. Now you will see an empty subprocedure called Button1_Click(). This is the sub-procedure that will be executed when the button is clicked.
Since it is empty, nothing will happen.
The only piece of code you need add, is the name of the macro your ported earlier into "Module1". If the macro
name was ReadData() (for instance) then all you need insert is
Sub Button1_Click()
ReadData
End Sub
Now we have finished editing the button properties and methods, return to the worksheet containing the button, and click
on the button. Possibly nothing will happen, why? You have created your macro in Module1, but you want to access it
from Button1_Click() in Module2, which is a different module. Hence your macro in Module1 MUST be declared as
7/8
Public so that it can be called and executed from Module2. Make it Public and then click the button again. It will
work now.
More functionality
Make your spreadsheet manual rather than automatic. That is select Tools->Options and on Calculation select Manual.
1.
2.
Click on the button again, and import the data. Nothing will happen until you force the spreadsheet to update its
calculations with Command+=.
Repeat the exercise above, creating a second button, with the caption Update. For the Button2_Click() subprocedure simply type
Sub Button2_Click()
Application.Calculate
End Sub
When this button is selected the spreadsheet will perform all its calculations.
Enough functionality already!
Create a button with the caption Save, which when clicked will save the entire spreadsheet to a name. This macro will
require the reverse of what had to be done for the ReadData macro. You should make most of the macro by recording
your actions while saving.
8/8
Download