Excel at Excel Excel Macros Workshop Introduction Using macros is a very basic way to automate a series of steps that are repetitive and time consuming. For example, let’s say you work at a local smoothie store and your fruit suppliers send you an excel spreadsheet of prices and products every week. The excel document is always formatted in the same way, but your manager hates reading the numbers and tells you to send him a chart. Instead of doing this by hand every weekend, you can create a macro that will do it for you. For this workshop, we will teach you the basics of Excel Macros. Do remember that Macros can be used in any of the Microsoft Office Programs. This workshop specifically teaches Excel Macros because companies most often use Macros in Excel and anyone could end up using Excel at work, regardless of your major. Macros in Excel are written in VBA (Visual Basic for Applications). In other words, if you have ever taken Visual Basic in any of your classes, the code itself will be very simple for you to learn. Even if you’ve never seen Visual Basic before, the logic is very easy to learn. Note: These instructions have been made specifically for PCs running Office 2010 or above. If you are using a Mac (and are not running Windows) or using an older version of Excel, you may find that certain buttons are on different tabs or options are different from what is shown in the instructions. Materials We will be using 3 documents in this workshop. (1) Please go to TexasMisa.com/excel-at-excel-materials (2) Download Material 1, 2, and 3 by clicking on the links. (3) They will be saved in your “Downloads” folder on your local device. You should see the following documents in your folder: Printer Sales 1 Sprinter Sales 2 Macro Excel Data Set Up In order to learn how to use Excel Macros, you will need to set up your Excel to let you create and edit macros. The first thing you need to do is set up the “Developer” Tab. If you’ve never used macros before, you probably won’t see a “Developer” Tab on your Excel ribbon. In order to manage your macros and other tools, you will need to make this viewable. To do this… (1) Go to “File” (the circular Microsoft Button on the top left-hand corner of Excel), then click “Options” (2) On the left-hand navigation, you should see a menu item called “Customize Ribbon” (3) Check the box next to “Developer” and Click OK.. (4) You should see the “Developer” tab in the ribbon! Now that you have set up your “Developer” Tab, you have to enable Macros. Since Macros runs code behind your Microsoft software, Excel automatically disables all Macros to protect your laptop from being damaged by malicious programs. To enable macros, you will need to do the following … (1) Go to “File”, then click “Options” (2) In the left-hand navigation, you will find “Trust Center”. Click on “Trust Center Settings…” (3) Click the radio button next to “Enable all macros” and click OK. Hooray! Now you can use macros. Let’s get started! Exercise #1: How to Record a Macro Let’s get into the exercises and learn some Macros! This exercise will teach you how you can create a Macro without any coding knowledge, and how you can use them to recreate previous tasks. (1) Open the first file: “Printer-Sales-1”. (2) You should see Columns “A” through “E” are filled in. Go to the “Developer Tab” and click “Record Macro” (3) You’ll get a popup asking you to name the Macro and enter some other information: (4) Let’s set the Macro name as “Sales” (5) Now, for the shortcut key, click on the textbox, hold “Shift” and press “S”. The shortcut key should now say “Ctrl + Shift + S”. NOTE: this shortcut key replaces all other shortcuts you may have when excel is open. For example, if you save this with a shortcut of Ctrl + C, you will no longer be able to use that to copy text while you are using Excel. Every time you press that shortcut key, this Macro will fire off instead. A tip is to click Shift and then a letter, let’s say S, so that you don’t override another shortcut key. (6) Set the description as “Format, Sum, and Chart”. (7) Click “OK” (8) You should now see the stop button at the bottom of the screen. This means your macro is being recorded! NOTE: Everything you do while recording macros is saved. So if you click on every cell in Excel, the macros will remember. Therefore, try not to do anything that is unnecessary! (9) Select the first row with titles by clicking the “1” on the left hand side of the Excel Spreadsheet. Now click “Sort & Filter” on the “Home” Tab and click “Filter” from the dropdown. If you are using a Mac, you will find this in the “Data” tab. (10) Click on the arrow next to Product and sort A-Z (11) Firstly, in column F and G, let’s put titles “Products” and “Totals”. In column F, copy and paste every new product you see in the Product column (C) (12) In the first cell under “Totals”, let’s use the SumIF function. The SumIF function asks you for a range (they data it will look at ), the criteria (what criteria the data must suffice to be added into the SUMIF, and the sum range (what quantities should be summed if the data meets the criteria. So, what does that mean for our example? First, your range is what the function looks at (every product name in the C column). Now, it checks if a product name is the same as the product in the cell you selected (green). If it is the same, it will add up the numbers in your quantities column (the numbers in the D column). The function in the cell should be: =SUMIF(C:C, F2, D:D) (13) Do that for every row in the Totals column. Click on the bottom-right corner of the cell and drag down. This should copy the function to every row in the Totals Column. (14) Now let’s change the colour of these two columns…because we can. This step is pretty pointless, but you can see how the Macros gets recorded. (15) The next step is to create a chart of the data that we formatted. Highlight the data in column F and G and go to the insert tab. Click ”Pie” and choose the first 2D Pie Chart that you see in the dropdown menu. You should now have a pie chart in the center of your page. (16) Let’s move it to a new page. Go to the “Layout” Tab and change the chart name to “Sales Chart” (17) Right click on the white space on the chart and click “Move Chart” (18) Click the radio button next to New Sheet, name it “Sales Totals” and click OK. Remember to change the name of the sheet! If you leave it with the default name, Macros tends to have issues. Click “OK” (19) Now you should have a new page with the pie chart. (20) Go to the “Design” Tab and click on any of the pie charts that display percentages (21) Now you have a chart with percentages! (22) Let’s click STOP to stop recording macros (23) The bottom left corner should now show this symbol. That symbol means your macros is no longer recording your actions. (24) Now let’s see if that worked. (25) Delete the Sales Total Sheet (26) Delete the Products and Totals and make the columns have no color fill again (27) Your excel spreadsheet should look exactly like it did before you started. (28) Use your shortcut key. Press Ctrl + Shift + S. (29) You should end up with the same results as when you went through each step manually! (30) Let’s save this. (31) Click Save As. Remember to make this an “Excel Macro-Enabled Workbook” and click Save. (32) Let’s move on to the next exercise. Don’t close this workbook! Exercise #2: Using Macros across Different Spreadsheets All of the effort we put in when doing the previous exercise would be pretty useless if you couldn’t use it in another excel document. This exercise will show you how to use macros from another Open workbook. (1) Go ahead and open Printer Sales 2. (2) Go to the “Developer” Tab and click “Macros” (3) Click “All Open Workbooks” in the dropdown. You should see the macros you made before in Printer Sales 1 (4) Select the “Sales” macro and click “Run”. It should be able to run the same tasks that we completed in Printer Sales 1. (5) This is one way for you to transfer the usage of macros from one file to another. Exercise #3: Loading and Formatting Data One of the materials you downloaded for this workshop was the Macros Excel Data, which is a CSV file (comma-separated values file). In other words, this is a document that has a bunch of data separated by commas. Instead of having tables, the data might look like this: Value 1, Value 2, Value 3, Value 4 101, 102, 103, 104 1423, 1643, 1234, 3475 Since this is extremely hard to read, this exercise will show you how you can import data from these files and make them readable on Excel. (1) Open a new excel spreadsheet. (2) Go to the “Developer” Tab and Click “Record Macros” (3) Name it “LoadData”. Click OK (4) Go to the “Data” Tab and click “Get External Data”. From the list, click “From Text”. (5) Select the “Macro Excel Data” file that you downloaded before and click “Import” (6) You will see a popup. Click “Next” (7) As mentioned previously, this file was separated by commas. Select “Comma” by clicking on the checkbox and click “Next” (8) Click Finish (9) Click OK (10) Click STOP to stop recording macros. (11) Now let’s create a new macro that will process some of this information. Click “Record Macros” and name this “GetTotals” (12) In column L, M, and N put the title “Sums” “Averages”, and “Medians” (13) In the first row under Sums, use the SUM function to get the sum of every record in the row. Do the same with the Average and Median functions (14) Select the three cells that you just wrote functions for. Click the bottom righthand corner and drag down to the end of the data. This should copy your functions to the other cells. (15) Now, write “Totals” in the bottom cell of the K column. Write a SUM function the get a sum of the entire column for columns L, M, and N (16) Click STOP. (17) Now, erase everything from this spreadsheet (18) Let’s run both the macros. Go to the “Developer” tab and click “Macros”. Click “LoadData” and click “Run”. (19) Do the same thing as in step 18, but click “GetTotals” and click “Run” (20) You should have everything that you did manually! This can be used to load data files that are formatted in a very specific way. If you know you will receive a file that is delimited by commas, this is an easy way to make the data readable as a table. Exercise #4: Writing Macros with VBA Since we’ve looked at the basics of Macros, let’s take a look at the code behind the Macros. As we mentioned before, Microsoft Macros uses Visual Basic for Applications. That means that Macros is capable of doing very complex tasks. However, in order to do this, you need to understand the basics of using the code. This exercise will teach you the basics of writing a Macros, without using the record function, and what some of the code means. (1) Let’s open a new Workbook and click “Macros” on the “Developer Tab. Type in “Heading” in the name area and click “Create” (2) When you click “Create”, you will see a blank page with the following words: Sub Heading() End Sub This page is a VBA page, meaning everything you write in here will be visual basic for applications. (3) Now, you want to add code so that your page looks like this: This is the code: Sub Heading() Dim label As Variant label = InputBox("Enter Name") Range("A1").Value = label label = InputBox("Enter Class") Range("A2").Value = label label = InputBox("Enter Date") Range("A3").Value = label End Sub Sub Auto_Open() Heading End Sub This looks very complicated, but it’s actually very simple when you get into it. Let’s go through this line by line. (a) In VBA, when you want Excel to do a specific task, you can create a Sub. The first line we wrote says that this is a sub with the name “Heading”. When you want to use this sub, you will be able to call it by using its name. You’ll see an example of this further into the code. Sub Heading() (b) In order to create a variable in VBA (a storage location for data), you first need to declare that variable. You can’t put something into a box if you don’t have the box. In the same way, VBA will not allow you to enter data into a variable unless you declare the variable. Until then, the variable does not exist for VBA. This code Dim’s (declares) the variable with the name “label” as the datatype of Variant. Variant means any type of data (whether it’s a number of a date) can be saved into this variable. Dim label As Variant (c) The next section is very repetitive, so let’s go through the basics. “label” is the name of the variable we created in the previous line. “InputBox(“Enter Name”) means that a textbox (or Input Box) will appear with the words “Enter Name” and a space for you to enter information. You will see how this looks when we run the code. A single equal sign (=) in VBA does not mean that one is equal to another. It means that you want to take the value from the right side of the = and put it into the variable on the left side. In other words, the variable “label” will now hold whatever the user inputs into the input box. label = InputBox("Enter Name") Range(“A1”) is the cell A1 in excel and .value means whatever information is inside the cell. Therefore, if we read it like we did the previous line, this means that cell A1 will now say whatever was saved in the variable called “label”. Range("A1").Value = label If we look at that in sequence, we asked the user for their name, saved it in the variable “label”, and then put the name into cell A1. This is repeated for the next few lines, although the Input Box asks for different information. label = InputBox("Enter Class") Range("A2").Value = label label = InputBox("Enter Date") Range("A3").Value = label (d) Since that is all we want this sub to do, we tell VBA to stop running the sub at this point by writing End Sub. End Sub (e) Now, we are creating a new sub and calling it Auto_Open. Auto_Open is actually a name for a sub that Excel recognizes. If there is a sub called Auto_Open, Excel will run this when it opens the document. Sub Auto_Open() (f) When this sub runs, we want it to call the Heading sub, which will make the Heading sub run. Heading (g) Since that is all we want this sub to do, we tell VBA to stop running the sub. End Sub (4) Now that you understand what all the coding meant, let’s save this as an Excel Macro-Enabled Workbook so that our macros run the next time we open it. (5) Close this document and open it again. (6) Now you should see the following prompts! Fill them in with your information. (7) The workbook should now look like this, with your own information, of course. Congratulations on coding your first Macro! Exercise #5: Importing Data from the Web Now that we’ve seen what the basic code looks like, let’s use it for a more complex function. We will look at how to import data from the web and be able to modify a Macro that we have already recorded. This exercise will give you a basic look at the code and teach you how to alter existing Macros. Note: This does not work if you’re on a Mac & not running Windows! (1) Let’s open a new Workbook and click “Record Macro”. Name this “GetStocks” (2) For this exercise, we’re going to use stock information from Yahoo Finance. To do this, go to the “Data” tab, click “Get External Data”, and click “From Web” (3) In the “Address Bar”, type in “Yahoo.com” and click “Go” (4) Click “Finance” Note: If you happen to get this error, click “Yes” and proceed! (5) Type “Goog” into the Searchbox and select Google Inc. (6) Select “Historical Price” (7) Scroll down until you see the prices table. Click the arrow next to the table and click import. The Arrow should turn into a green check (8) Click OK (9) You should see the historical prices for Google in your Excel Spreadsheet! (10) Click STOP to stop the macro from recording. (11) Go to the “Developer” Tab, click “Macros”, select “GetStocks”, and click “Edit” (12) You should see the following (13) This is the Macro that you just recorded. This sub has recorded how to go to the web and import the historical prices for Google. Now, let’s make changes so you can pull the historical prices of any company on Yahoo finance without ever going back to the website. Get ready to do some coding! (14) First portion! Add the following code beneath “GetStocks Macro” Dim TickerSymbol As Variant TickerSymbol = InputBox(“Enter a Ticker Symbol”) Before going on, let’s explain what this code means. This code Dim’s (declares) the variable with the name “TickerSymbol” as the datatype of Variant. Now that you have declared the variable, you need to enter data. The variable, Ticker Symbol, is given the data that we get back from an input box. What this means is that a popup will appear, prompting the user to enter information. The popup will say “Enter a Ticker Symbol”. When you enter a ticker symbol and click “OK”, the TickerSymbol variable will save that information. We need to do this in order to let the user enter the ticker symbol of any company they want, and let Excel handle the rest of the work. (15) Second portion! Replace both instances of “GOOG” with the following code: “ & TickerSymbol & “ (16) The above two instances of GOOG should now look like this What does this do? If you look at the code, it says ActiveSheet.QueryTables.Add(Connection:= and then the website URL in quotation marks. Excel is going to this URL and looking for the table you want to import. In the next line, we see that the code says .Name= and then the name of the table we selected in quotation marks. In this part of the code, Excel looks for a table at the URL with this specific name. By changing GOOG to “ & TickerSymbol & “ we’re altering the URL and the table name to look for the prices of the company we want rather than Google. Now, the quotation marks might be a little confusing. IN VBA, any code encased in quotation marks is considered a “String”. Similarly to how Excel allows you to write whatever you want in cells, but considers it to be a function if you have the “=” sign before it, VBA differentiates functions and normal words as well. In other words, if you put TickerSymbol instead of “ & TickerSymbol & “, VBA will interpret this to mean the URL is “Beginning of URL Ticker Symbol End of URL” even if you enter an actual ticker symbol. That’s not what we want. We want the ticker symbol name to be added to the URL. The & sign allows you to connect the data in variables to a string. If we use the code that was written in step 13, The URL string will now look like this: “Beginning part of the URL ” & TickerSymbol & “ End of the URL” If you were to input AAPL when Excel prompts you for a ticker symbol, VBA would interpret the URL string as “Beginning part of the URL AAPL End of the URL” (17) Now, let’s add code so that Excel will run this Macros when the Excel document is opened. To do this, add the following code below “End Sub” Sub Auto_Open() If you press enter, Excel should automatically write End Sub below your code. Auto_Open is a function that Excel recognizes. If there is a macro called Auto_Open, Excel will run this when it opens. (18) Since we want the GetStocks function to run when the excel document opens, add the following code between Sub Auto_Open() and End Sub GetStocks When the Auto_Open macro runs (as soon as you open this excel document), it will CALL the GetStocks macro (which means it will run the GetStocks macro) (19) Now, let’s save this as an Excel Macro-Enabled Workbook (20) Delete all of the stock information that was on the Excel spreadsheet (21) Save and close the file. (22) Open it again. You should get this popup. This is the InputBox that you wrote into your code. (23) Enter “AAPL”, or any Ticker Symbol that you know exists in Yahoo Finance, and press OK (24) Excel should load in the historical prices of that stock! WRAP UP This workshop was a basic introduction to what Macros are capable of. As always, you can find much more information if you look for Youtube videos or tutorials online. We hope this workshop helped you get a taste of Macros and made it easier for you to get started! Any questions or feedback about the workshop can be directed to our officers. Workshop and Content Brought to you by MISA 2014 - 2015