You are on page 1of 9

Advanced Macros in ExcelBeginners Guide

IF you are to really learn just one Office application, then you should choose Excel. Because it is the most versatile and powerful of all the Office applications. With Excel you can almost get rid of the other Office applications all together. A side from the normal calculations you can write letters, create databases with powerful reports and analyze tools, create useful forms for everyday chores, and program powerful small applets. Within certain limits of course.
Using Advanced Macros

Most users have come across the word MACRO, one time or another using Excel. A macro is a recording of sorts, that stores your actions, step by step. Macros are used to eliminate the need to repeat the steps of common tasks over and over. Tasks such as adding or removing rows and columns, selecting a range of cells, or changing textcolor, fonts etc. In Excel, macros are written in Visual Basic for Applications (VBA). For those who cannot write VBA code, Excel allows you to record a series of steps using keyboard and mouse that Excel then converts into a macro. In a few upcoming articles I am going to show you how you can create powerful and effective macros that hopefully will take your Excel experience to another level. How about letting Excel Copying Sheets, renaming them, Choose filenames, choosing between file locations and save the document as PDF sound ?
Sounds interesting ?

Great, lets get started


For most users, macros are an unvisited territory. Some try to record a macro and never see the full potential in it or the usage for it. And some, create macros of tasks they do repeatedly, over and over. Like formatting cells, copying formulas etc. And it ends there. Not so any more. Built into the MS Office Platform you will find something called VBA (Visual Basic for Applications). This is a light version of the programming language adjusted to work within each application (and across). And this is where we can harness the power of Excel. Imagine being able to Export/Import data between Excel and Word, creating automatic reports and letters. Programming Office to your needs.

Programming ???

Dont despair it is not as hard as it sounds. By combining the Macro Record functionality, with some small coding efforts you will come a long way. Learning as you go. Before we get into that, lets record a Macro.

Record a Macro
I am using the new Office 2010 in these examples, but you may use any Excel version you choose. However, not every icon or menu will have the same name and/or appearance, though the functionality will remain mostly the same.
I use the Excel cell references like this:

[B2] = Click on this specific Cell [B2:C3] = Highlight these Cells

Open a blank Excel Document and click on the VIEW-Ribbon. All the way to the left is the Macro Button. Click on the little black arrow underneath the Macro Icon, and choose: Use Relative References. This setting allows us to use the macro anywhere we like, as opposed to a set area in the worksheet. NOTE! If you have Excel PRE 2007, you will not have the Relative References choice. You must instead, select the cells BEFORE recording the macro to avoid it locking to specific Cells.

Click the little black arrow (under the macro icon) again. This time, choose Record Macro. Call it First, Click OK.

Now, Click on a Cell [B2], and type: This is My first Macro Recording. (Normally, you wont be typing text when recording macros but, in this example we are). Select a sample of cells around the text you wrote [B2:D3] (if you dont use 2007/2010, hold down the SHIFT key and create the selection using the arrows, right and down). Click on the HOME-Ribbon, and set text color to RED and Background Color to Yellow

Click the little black arrow once more, choose Stop Recording (In Pre 2007/2010 Excel you will have a small floating window, containing the Stop Recording-button).

Highlight a new cell [H5]. Click on the Macro Icon, showing a list of available macros. Highlight the Macro we just created and Click RUN. What you see is that Excel now replicates our steps, on a new set of cells. Choose a different Cell, and try it again to see that it works.

What the code looks like

To see what the code looks like, click the Macro Icon again, choose the macro and click EDIT. This will open the VBA editor and show your macro:
Sub First() ' ' First Macro '' ActiveCell.FormulaR1C1 = "This is my first Macro Recording" ActiveCell.Select Selection.Font.Bold = True With Selection.Font .Color = -16776961 .TintAndShade = 0 End With ActiveCell.Range("A1:D3").Select With Selection.Interior .PatternColorIndex = xlAutomatic .Color = 65535 .TintAndShade = 0 .PatternTintAndShade = 0 End With End Sub

What you see is the VBA-Code necessary to do the task you recorded (it may differ from this example). We will get back to the code later. But if you want to play around with this, try changing these settings (marked RED in the example):

.Color = -16776961 -> .Color = -16776981 .Color = 65535 -> .Color = 255

Close the VBA Editor and run the Macro again.

Next Part
This is part two of a new series Im writing, teaching you how to get more functionality out of your Excel. If you are not familiar with Macros I suggest you read the first part, before beginning on this one.

In Part Two

In this part we are starting off using some of the commands you should know, and then create a Macro that decide filename, which folder to use, before exporting the document to PDF-format. I am also going to show you how to create a button to trigger the macro. As in the first part, I am using Office 2010. Even though the code and programming are the same in older versions of Excel, the images and buttons may differ from what you see on your screen. Enough Chit Chat, lets get this party started

Quick Introduction to VBA and Excel

As mentioned earlier (in the first Part) VBA is Visual Basic Light. The programming language is object-oriented, meaning we create code that relates to objects like Cells, Sheets and Workbooks. Each Object has many functions (or actions) and each function has settings we can use; like Object Name, Value, Id etc. Dont worry about remembering them all, VBA has a built-in tool that show you a list of available settings for each function.

In addition to the objects we are going to use what we call Variables. Variables temporarily store data we are going to use later (think of it as small post-it notes). To keep track of our variables we declare them (give them names). This is usually done in the Macro Header. We will get back to this later. One last thing: In VBA we dont use the name Macro. Instead we call it SUBS. The Sub has a begin-code and an end-code, which declare the Macro Name and End: Sub EmptyIt() Content Here End Sub
Some of the functions we are going to use

Every function we use will trigger an event inside the Excel workbooks. When using Excel you maneuver within Cells and Sheets. Each time you Select a Cell it becomes Active. Instead of Clicking on a cell, we can tell the macro to do it for us. First, we tell the macro which Cell to activate, using the function RANGE (Cell reference enclosed in parentheses and quotes). Then we tell it what we want to do; click it. The code looks like this: Range(B2).Select (or Range(B2).Activate) To WRITE something in that Cell we have to use a different function: ActiveCell. ActiveCell.Value =Write this into the Cell

To READ the contents of the Cell we need to use a variable. As mentioned earlier the variable has to be declared (given a name). Then we can write something in it. The code would look like this: Dim CellContent CellContent = ActiveCell.Value Then we can use that information later on even if the content of that cell should change. To Move between workbooks or Sheets we use the functions called: Sheets or Workbook, like this: Workbook(prices.xls).Activate Sheets(Calculations).Activate

Creating a Macro
Now we should be ready to create our PDF Macro. For this lesson I have created a document containing a simplified order form. You can download it at the end of this article. The workbook contain the macros used in these articles. The first macro has been created using the RECORD MACRO function.

To make the macro as versatile as possible we are going to create a new worksheet: Settings. This Sheet is going to store information like default filename, default save-to folder(s), and order handler. Later we can add functionality like Open After Save, Overwrite existing etc. This will allow other users to change settings without having to edit the macro.
1. Rename your main sheet to Form (Right click the sheet tab, choose Rename). 2. Create a new worksheet within your document, rename it: Settings. 3. In the workbook add some Labels to describe what information to store, and fill in the default values. (See example). 4. Return to the Form Sheet (The main sheet)

5. To create a new Macro, Click on the Macro Icon. In the Text box, type in the name for the Macro: CreatePDF and Click the Create-Button.

In the VBA-Editor you will now see an empty Macro, looking like this: Sub ToPDF() End Sub All our code will go in-between these two lines. First we declare our post-it notes (variables):
Dim Dim Dim Dim Name As String Stamp As String WhereTo As String sFileName As String

Now we need to retrieve data from the Settings Sheet, add the following lines:
Sheets("Settings").Activate Range("B5").Activate WhereTo = ActiveCell.Value Range("B7").Activate Stamp = ActiveCell.Value If Stamp = "" Then Stamp = Date

The Cell references B5 and B7 may differ from your settings sheet. Use the apropriate cell references. Then we will retrieve the customer name from the form:
Sheets("Form").Activate Range("E5").Activate Name = ActiveCell.Value

Next, we put the data to good use, by creating the filename:


sFileName = WhereTo & Name & "_" & Stamp & ".pdf"

sFileName, WhereTo, Name and Stamp are the variables we use. The = sign means that the following information is to be stored. We link the information from each variable using the &-sign. Text is added between the quotes. The finished variable could look like this: sFileName = "C:\Sales\Thomas_09092010.pdf". Last Thing we do; add the Save To PDF Command:
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _ sFileName, Quality _ :=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _ OpenAfterPublish:=True

Create Button

Okay, before we test that everything works, lets make a button to trigger the macro. In order to do this (in Office 2010) we need to activate a hidden Tab on the ribbon (older Office, look for Form Controls).
1. 2. 3. 4. Click on the Green File Tab Choose Options In the Options Dialogue, click Customize Ribbon In the List Window to the right, there is a list of all the available Ribbons. Locate the one Called: Developer and Check the box next to it 5. Click OK to Save

Activate (Open) the Form Sheet, and click the Developer Tab in the Ribbon. In the middle of the Ribbon there is an icon called Insert. Click the little black arrow below it. In the pull down menu, choose the first element that looks like a little grey button. With the crosshatch pointer, draw a button somewhere in the Sheet. This will trigger the Form Button Event Menu. Choose the Macro you would like to run, and Click OK.

Now that the button has been created, we need to edit the Button label. With the button still activated, click the button text. This will allow you to type directly on the button. Write something clever on it, then press Enter.

Click somewhere on the sheet, to disable the button edit function, and to activate the button. Now, all that is left, is to save your document. Make sure you save it as a Macro Activated Excel Document (xlsm).

DOWNLOAD

This File: Documents contains both an 2010-Version (xlsm) and the XP-Version (xls).
Next Part

Part 3, will take this macro functionality longer. We will add Error handling, and make sure we dont overwrite existing files. We will add more settings to the Settings sheet. Then we will add another Macro just for fun.

You might also like