Download presentation
Presentation is loading. Please wait.
Published byHannah Shelton Modified over 8 years ago
1
Macros in Excel Using VBA Time Required – 5 hours
2
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
3
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 programming language that gives you the ability to extend those applications-tasks VBA works by running macros, step-by-step procedures written in Visual Basic You can also use VBA to build new capabilities into Excel (for example, you could develop new algorithms to analyze your data, then use the charting capabilities in Excel to display the results) Macros: A macro is a recording of each command and action you perform to complete a task. Then, whenever you need to carry out that task in a spreadsheet, you just run the macro instead.macro Why Excel-VBA
4
Bringing up the necessary tabs Developer Tab To enable the Developer tab… On the File tab, choose Options to open the Excel Options dialog box. 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 Basic, Macros, and Macro Security buttons on the tab. Note: Students do it As the teacher explains
5
NOTE: Security Warning: Macros have been disabled bar appears between the ribbon 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 Excel file format (.xlsx); instead, you must save the macro in a file with a special extension,.xlsm.
6
Visual Basic Editor This following procedure shows you how to create a new blank workbook in which to store 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 macro already typed in.
7
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
8
Go back to the Developer tab in Excel and click the Macros button again. Select the Hello macro in the list that appears and then click Run to display a small message box that contains the text, "Hello, world!" You just created and implemented custom VBA code in Excel. Click OK in the message box to close it and finish running the macro.
9
A Real-World Example Suppose that you have a workbook that contains lists on a large number of worksheets and that you want to change the name of each worksheet to match 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 each worksheet to see if it has a list, copying the name if it does, clicking the worksheet tab, and then pasting in the new name. Instead of performing all of those steps manually, use Excel VBA to rename the sheets automatically.
10
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 choose Edit 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").Select Sheets("Sheet1").Name = "New Name" End Sub
11
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 Sheets collection object. The last line of the recorded macro modifies the Name Property of the Sheet1 member of the Sheets collection. This is the line to keep. After you make your changes, the recorded code should now look like the following.
12
Sub RenameWorksheets() Sheets("Sheet1").Name = "New Name" End Sub Observe -Manually change the sheet called New Name back to Sheet1, then run the macro. The name should change back to New Name. End Of Lab 1
13
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 up with on your own. Lab 2 Review What is a Macro, How to bring up a developer tab, How do you save a file (format)
14
Another way to Record Macros
16
If you have assigned a keyboard shortcut to a macro then you can run it by holding down the CTRL key and pressing the associated letter.
17
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 only then the following statement is executed. -A loop is a sequence of statements which is specified once but which may be carried out several times in succession. The code "inside" the loop (the body of the loop)is obeyed a specified number of times, or once for each of a collection of items, or until some condition is met, or indefinitely.indefinitely Looping One limitation of the code up to this point is that it only makes a change to one worksheet. You could add another line for each worksheet that you want to rename, but what if you do not know how many worksheets there are, or what their current names are? You need a way to apply some rule for each sheet in the workbook.
18
VBA has a construction called a For Each loop that is ideal. The For Each loop examines each item in a collection object such as Worksheets and can be 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 look for ideas if you get stuck working on code.VBA Language Reference Using the third example in the "Using For Each...Next Statements" topic, edit the macro so that it looks similar to the following code.
19
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 worksheet in 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, change the line to the following. myWorksheet.Name = myWorksheet.Name & "-changed" Instead of trying to give each worksheet the same name, this line changes the current name of each worksheet (myWorksheet.Name) to the current name with "-changed" appended to it.
24
To test the macro, rename the worksheets back to Sheet1, Sheet2, and Sheet3 and delete the contents of cell B1 on one or more of the worksheets. Run the macro to verify that it renames the worksheets that have text in cell B1 and leaves the other worksheets alone. The macro works for any number of worksheets, with any combination of populated and empty B1 cells. Assignment 2: (100 points) Hand the handout too create a table of names of persons and corresponding heights. The job is to find the height of the tallest person.
25
Question: Check if the table is created correctly Ask them how would they calculate the average height of all students Where/which formula will they use? (Ask them to show you ) ( 30 points) LAB # 3 contd…
26
Expected Ans: Use the average function to take in the range of cells and divide by the total number 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 is the tallest. Then proceed to the next pair. Compare the value store with the new values. 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 the tallest)
27
Teach the students how to write it using Macros- Discuss, explain the terms and what they mean and write the code with the help of 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
28
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.
29
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 gets grade B -if the average is greater than or equal to 70 and less than 80 the student gets grade C -if the average is greater than or equal to 60 and less than 70 the student gets grade 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)
30
Bibliography: http://msdn.microsoft.com/en- us/library/ee814737.aspx#odc_Office14_ta_GettingStarte dWithVBAInExcel2010_MacrosAndTheVisualBasicEdit or http://msdn.microsoft.com/en- us/library/ee814737.aspx#odc_Office14_ta_GettingStarte dWithVBAInExcel2010_MacrosAndTheVisualBasicEdit or ttp://www.addictivetips.com/microsoft-office/how-to- create-a-simple-macro-in-excel-2010/ http://spreadsheets.about.com/b/2011/03/24/excel-2007- macro-tutorial.htm http://spreadsheets.about.com/b/2011/03/24/excel-2007- macro-tutorial.htm http://msdn.microsoft.com/en-us/library/ee814737.aspx
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.