Macros in Excel
Using VBA
Time Required – 5 hours
   Outline-Lab 1
Why Excel? Why Macros
Use of Developer Tab
-How to access it and use it-why
  Why use Macros
How and where to type a macro
Run a macro
Save the file
Powerful tool that you can use to manipulate, analyze, and present data
Easier way to perform repetitive tasks
Excel have Visual Basic for Applications (VBA), a programminglanguage that gives you the ability to extend those applications-tasks
VBA works by running macros, step-by-step procedures written inVisual Basic
You can also use VBA to build new capabilities into Excel (forexample, you could develop new algorithms to analyze your data, thenuse the charting capabilities in Excel to display the results)
Macros: A macro is a recording of each command and action youperform to complete a task. Then, whenever you need to carry out thattask in a spreadsheet, you just run the macro instead.
Why Excel-VBA
 Bringing up the necessary tabs
Developer Tab
To enable the Developer tab…
      On the File tab, choose Options to open the Excel Options dialogbox.
      Click Customize Ribbon on the left side of the dialog box.
      Under Choose commands from on the left side of the dialog box,
       select Popular Commands.
       Under Customize the ribbon on the right side of the dialog box,select
       Main tabs, and then select the Developer check box.
       Click OK.
      After Excel displays the Developer tab, note the location of the
       Visual BasicMacros, and Macro Security buttons on the tab.
Note:
Students do it
As the teacherexplains
Developer tab in Excel 2010
NOTE:
Security Warning: Macros have been disabled bar appears between theribbon and the worksheet when you open a workbook that contains a macro,you can click the Enable Content button to enable the macros.
Also, as a security measure, you cannot save a macro in the default Excelfile format (.xlsx); instead, you must save the macro in a file with a specialextension, .xlsm.
Visual Basic Editor
This following procedure shows you how to create a new blank workbook in which tostore your macros. Save the workbook in the .xlsm format.
To create a new blank workbook
Click the Macros button on the Developer tab.
In the Macro dialog box that appears, type, Hello under Macro Name.
Click the Create button to open the Visual Basic Editor with the outlines of a new macroalready typed in.
The Visual Basic Editor contains the following code.
Sub Hello()
End Sub
Sub stands for Subroutine, which you can define for now as "macro".
Running the Hello macro runs any code that is between Sub Hello() and End Sub.
Now edit the macro so that it looks similar to the following code.
Sub Hello() MsgBox ("Hello, world!") End Sub
Go back to the Developer tab in Exceland click the Macros button again.
Select the Hello macro in the list thatappears and then click Run to displaya small message box that contains thetext, "Hello, world!"
You just created and implementedcustom VBA code in Excel. Click OKin the message box to close it andfinish running the macro.
A Real-World Example
Suppose that you have a workbook that contains lists on a large number ofworksheets and that you want to change the name of each worksheet tomatch the heading of the list on that worksheet.
Not every worksheet has a list on it, but if it does, the heading is in cell B1,and if it does not, cell B1 is blank.
The names of worksheets without lists should be left alone.
Ordinarily, this could be a complex task that involves looking at eachworksheet to see if it has a list, copying the name if it does, clicking theworksheet tab, and then pasting in the new name.
Instead of performing all of those steps manually, use Excel VBA to renamethe sheets automatically.
To record a macro that renames a worksheet
Click Record Macro on the Developer tab.
Name the macro RenameWorksheets,
Rename Sheet1 to New Name, and click Stop Recording.
Go to the Developer or View tab, click the Macros button, and chooseEdit to open the Visual Basic Editor.
The code in the Visual Basic Editor should look similar to the following.
Sub RenameWorksheets()
 
' ' RenameWorksheets Macro ' ' Sheets("Sheet1").SelectSheets("Sheet1").Name =
"New Name"
End Sub
Comments:
Any line that begins with an apostrophe is a comment and
has no effect on what the macro does.
The main uses for comments are the following:
To make the code easier to understand, not just for you,
but for anyone else who might need to modify the code later.
To temporarily disable a line of code (called commenting it out).
The next line uses the Select method to select the Sheet1 member of the Sheetscollection object.
The last line of the recorded macro modifies the Name Property of the Sheet1 memberof the Sheets collection. This is the line to keep.
After you make your changes, the recorded code should now look like the following.
Sub RenameWorksheets()
Sheets("Sheet1").Name = "NewName"
End Sub
Observe -Manually change the sheetcalled New Name back to Sheet1, thenrun the macro. The name shouldchange back to New Name.
End Of Lab 1
Assignment 1                                                    (100 points)
Students:
Please write  a code- Macro to :
1) Display your name,
 2) Name of the school and its
 3) Address of the school
Run the macro and show it to the teacher.
30 points for each task and 10 points for something that you come upwith on your own.
Lab 2
Review
What is a Macro,
How to bring up a developer tab,
How do you save a file (format)
Another way to Record Macros
If you have assigned a keyboard shortcut to a macro then you can run it by holdingdown the CTRL key and pressing the associated letter.
Review of Excel.
How to use Developer tab and how to create Macros.
What is another way to record a Macro
Loops : Why and what are conditional statements and loops – students tell/explain-review
-A conditional statement has a condition and if the condition is true onlythen the  following statement is executed.
-A loop is a sequence of statements which is specified once but which maybe carried out several times in succession. The code "inside" the loop (thebody of the loop)is obeyed a specified number of times, or once for each ofa collection of items, or until some condition is met, or indefinitely.
Looping
One limitation of the code up to this point is that it only makes a change toone worksheet. You could add another line for each worksheet that youwant to rename, but what if you do not know how many worksheets thereare, or what their current names are? You need a way to apply some rule foreach sheet in the workbook.
 
VBA has a construction called a For Each loop that is ideal. The For Eachloop examines each item in a collection object such as Worksheets and canbe used to take an action (like change a name) to some or all of those items.
***For more information about the For Each loop, see the VBA Language Reference.Click "Visual Basic Conceptual Topics", then "Using For Each...Next Statements".Also, be aware that the VBA Language Reference, like the Object Model Reference,will amply repay the time that you spend browsing it, and is an excellent place to lookfor ideas if you get stuck working on code.
Using the third example in the "Using For Each...Next Statements" topic, edit themacro so that it looks similar to the following code.
Sub RenameWorksheets()
For Each myWorksheet In Worksheets myWorksheet.Name = "New Name" Next
End Sub
myWorksheet is a variable; that is, what it represents varies.
In this case, the myWorksheet variable successively represents each worksheetin the Worksheets collection.
You do not have to use myWorksheet; you could use "x", "ws","WorksheetToRenameAfterTheContentsOfCellB1", or (with a few restrictions)almost any name that you want. myWorksheet.Name = "New Name"
To correct the line so that you can verify that the For Each loop works, changethe line to the following.
myWorksheet.Name = myWorksheet.Name & "-changed"
Instead of trying to give each worksheet the same name, this line changes thecurrent name of each worksheet (myWorksheet.Name) to the current name with"-changed" appended to it.
To test the macro, rename the worksheets back to Sheet1Sheet2, andSheet3 and delete the contents of cell B1 on one or more of theworksheets. Run the macro to verify that it renames the worksheets thathave text in cell B1 and leaves the other worksheets alone. The macroworks for any number of worksheets, with any combination of populatedand empty B1 cells.
Assignment 2:   (100 points)
Hand the handout too create a table of names of persons andcorresponding heights. The job is to find the height of thetallest person.
Snipping Tool
Question:
Check if the table iscreated  correctly
Ask them how wouldthey calculate theaverage height of allstudents
Where/which formulawill they use?
(Ask them to show you )
( 30 points)
LAB # 3 contd…
Expected Ans:
Use the average function to take in the range of cells and divide by the totalnumber of people
Ask them to open the Macros or the developer tab-
give handouts
Ask them what steps would they use  logically …to find the tallest person
For tallest person:Ask questions:
Expected ans:
Compare the height of the first with the second and store the value of whoever isthe tallest. Then proceed to the next pair. Compare the value store with the newvalues. If another big value is found replace the stored value.
The tallest height and corresponding name is the tallest.
For added bonus (10 points they should tell the name of the person who is thetallest)
Teach the students how to write it using Macros-
Discuss, explain the terms and what they mean and write the code with the helpof questions and answers  on the board…
Sub Tall_person()
Dim tallest As Integer, tall As Integer, i As Integer
tallest = 0
For i = 2 To 11
   'ignore the two code lines below, they are only added to illustrate the loop
    Cells(i, 4).Select
    MsgBox "i = " & i
     If Cells(i, 4).Value > Cells(i + 1, 4) Then tallest = Cells(i, 4) Else tallest =Cells(i + 1, 4)
Next i
MsgBox "The tall person is  at row " & tallest
End Sub
Walk about and check whether the students are doing it corrrectly
Help/explain how to  them how to run the code
Review Questions:
1)Ask students how to open the developer tab
2)How to record a Macro
3)What is an integer
4)How do you identify a cell
5)Students continue to work on the previous lab.
6)Teacher walks around helping/explaining.
Lab # 4
Assignment # 3:
Create an excel spreadsheet with the names of 10 students in a class.
Each student has 3 subjects
Calculate the average for each student. (30 points)
According to the average..
-if the average is greater than or equal to 90 the student gets grade A
-if the average is greater than or equal to 80 and less than 90  the student getsgrade B
-if the average is greater than or equal to 70 and less than 80 the student getsgrade C
-if the average is greater than or equal to 60 and less than 70 the student getsgrade D
-if the average is less than 60 the student gets an F
(60 points)
Display the names of students with grade A. (10 points)
Bibliography:
ttp://www.addictivetips.com/microsoft-office/how-to-create-a-simple-macro-in-excel-2010/
http://msdn.microsoft.com/en-us/library/ee814737.aspx