Você está na página 1de 2

MrExcel.

com

With Relative Recording turned off, the resulting macro will always select J11. With Relative Recording turned on, the resulting macro will go down one cell from the current cell. Do you see how much more useful this macro is? The rst macro only works when you happen to be in J10. The second macro works anywhere except row 1048576. Turn Use Relative References on every day. (It resets back to off when you close Excel). This one is so important, it is shown twice, once in 2010 and once in 2013.

Excel Macro Recorder to VBA


Tips & Tricks from MrExcel

Unfortunately, Ctrl+Period wont correctly record jump to next corner of selection number.

Never Touch the AutoSum Button


You are at the bottom of a long column of numbers. When you click the AutoSum button, Excel builds a formula that extends all the way up the column. But the macro recorder does not record Do that awesome trick the AutoSum button does. Instead, it hard-codes exactly how many numbers were summed. For example, in the following gure, record a macro to add the total in B7 using the AutoSum icon. When you play the macro back in E9, it only sums the last ve numbers.

Show Developer Tab in Ribbon


While you could get by with the Macro drop-down on the end of the View tab, it is easier to use the Developer tab. In Excel 2010-2013, right-click the ribbon and choose Customize the Ribbon. On the right side, choose the checkbox for Developer.

Be Clever with Navigation


Every day, your data will have a different number of rows. This is the challenge in macro recording. You can get the macro recorder to move to the end of the data set by using the right navigation keys while recording. To get to the bottom of a data set, use Ctrl+Down Arrow. To select all data below the headings, go down to the rst cell, then Ctrl+Shift+Down Arrow then Ctrl+Shift+Right Arrow. If you instead simply click on the last row, Excel will record Go down 9 rows. If you use Ctrl+Down Arrow, Excel will record a macro that presses Ctrl+Down Arrow to move to the last row. Instead, turn on the macro recorder and type a formula of =SUM(A$2:A6). Would you ever type that formula in real life? No. But if you use that formula, the macro recorder will write a formula that goes from row 2 down to the row above the active cell.

Allow Macros
By default, macros will not run in Excel. Use the Macro Security icon in the Developer tab. Choose the second option, which is Disable All Macros With Notication. This sounds like this wont allow macros, right? It gives you a visible warning when you open a workbook that contains macros. You get to choose if you Enable macros or not. If it is a le that you wrote, you can Enable. If it is a le from an unknown hacker, you can leave them disabled.

Record Your Macro


Click the Record Macro button. You can provide: MacroName: You cant have spaces in the name. Use something descriptive like AddTotals. Shortcut key: Ctrl+B is already assigned to Bold. (All of the letters except Ctrl+J are already assigned). However, if you assign your macro to Ctrl+B, your macro will win and Ctrl+B will not do bold anymore. Idea: type Shift+B in the Shortcut key box to assign the macro to Ctrl+Shift+B. Store Macro In: if this is a general purpose macro, you can put it in Personal Macro Workbook. If this is a macro that only applies to the current workbook, store it in This Workbook. Description: this will appear as comments at the top of the macro in the VBA window. When you are ready, click OK. A square Stop Recording button will appear next to Ready

Macro Recording Rules


The macro recorder does a lousy job because of a few poorly chosen default settings. By following these rules, you can record macros that will work, day after day.

Other useful navigation that will be recorded correctly by the macro recorder: Ctrl+Home to return to A1. Ctrl+* to select current region. Ctrl+End to move to the last cell (although the macro version has the same problems as the Excel version) Ctrl+PgDn to move to next worksheet to the right. Ctrl+PgUp to move to previous worksheet.

Use Relative References


This icon should be selected every time you are recording a macro. If Microsoft wouldve turned this on by default, you wouldnt have had to buy this tip card. Say that you are in cell J10. Turn on the Macro Recorder. Press the Down Arrow key.

in the status bar in the lower left corner of your Excel screen. Anything you do will get recorded in the macro. If your manager walks in and asks you to open a report and print it, this will get recorded in your macro. When you are done with the steps, dont forget to click Stop Recording.

Save Final Row in a Variable


The macro recorder will never use a variable, but it is easy for you to set up a new variable. To gure out how many rows you have today, use: FinalRow = Cells(Rows.Count, 1). End(XLUP).Row Once you know FinalRow, you can create other variables: TotalRow = FinalRow + 1 RowCount = FinalRow 1 Note: End(XLUp) is like pressing Ctrl+h. Note: Rows.Count is the last row in the grid (usually 1048576 but only 65536 if the le is in compatibility mode). The 1 in the Cells function stands for column A. If you have notes below the data in A, or if A is sparse, you can use 2 for column B and so on.

Running the Macro


There are many ways to run a macro: Press the Ctrl+shortcut key that you assigned when recording the macro. (To change the key later, use Alt+F8, select the macro, then click Options) Display the Macros dialog box with Alt+F8. Double-click the macro. Find the macro in the VBA window. Click inside the macro, then press F5 or click Run button. the Assign the macro to a toolbar or ribbon button. Right-click either the QAT or Ribbon and choose to Customize. In the Customize dialog, change the left dropdown to Macros. Find the macro and add it to the QAT or Ribbon. Tip: Click Modify button at bottom of right list to change the icon. Assign the macro to a Command Button. On the Developer tab, open the Insert tab and choose Form Button. Drag a rectangle on the spreadsheet to draw the button. Right-click and choose Assign Macro. Assign the macro to any picture or shape. Right-click the object and choose Assign Macro.

Else Cells(i, 5).Font.Color = RGB(12,12,12) End if If you have to check for many different possible conditions, use Select Case ' Status Code is in column J Select Case Cells(i, j) Case "A", "B", "E" ' Do Something Case "C" 'Something else Case "D", "G" 'Something Else Case Else MsgBox Error in row " & i End Select

FormulaR1C1
The macro recorder does formulas in R1C1 style. You can switch .FormulaR1C1 to .Formula, or you can learn the cool R1C1 style: =RC refers to the cell that holds the formula. =RC[-3] refers to current row, 3 columns to the left of the formula. =R[1]C refers to current column, 1 row down. =R1C refers to row $1 of the current column =RC1 refers to column $A of the current row =R1C13 refers to $M$13

Refer to Ranges Using Variables


While the macro recorder might refer to Range("A5"), there is a more efcient way to refer to a single cell or a range of cells. Cells(5, 2) refers to column 2, row 5 or B5. Cells(5,2).Resize(1,7) refers to B5:H5. ActiveCell.Offset(0,-1) refers to the cell to the left of the active cell. Use the above with variables: Cells(TotalRow, 5) refers to column E of the total row. Cells(1,1).Resize(FinalRow, 10) refers to A:J for however many rows you have today.

Misc. Tips
Avoid Excel asking questions: Application.DisplayAlerts = False Worksheets("Sheet2").Delete Application.DisplayAlerts = True For faster macros, use Application.ScreenUpdating = False If an error is possible and OK, skip the error message. In the following example, you are trying to delete a text le. If the le is missing, Excel will stop and tell you that it can not nd the le to delete it. That means the le has already been deleted and there is no reason to stop the macro.: On Error Resume Next Kill ("C:\aaa\FileLog.txt") On Error GoTo 0

Loop Through All Rows


' Loop from row 2 to end For i = 2 to FinalRow ' Code here that refers to Cells(i, . Next i Be careful if the code in the loop will be deleting rows, you want to run the loop backwards: For i = FinalRow to 2 Step -1 ' Code to be repeated here Next i

Moving to VBA
There are several things the macro recorder will never do. Your strategy can be to rely on the macro recorder for 90% of your macro, and then add these items in the VBA window.

Open the VBA Window


Either press Alt+F11 or use the Visual Basic icon in the Developer tab. Your rst time in the VBA window, you should press Ctrl+R to display the Project Explorer pane. Expand the + next to your workbook and then next to Modules. Doubleclick Module1 to nd your recorded code. If you cant nd the code, go back to Excel. Use Alt+F8, click on the macro and then click Edit.

If Then Else Logic


For i = 2 to FinalRow If Cells(i, 5).Value > 1000 then Cells(i, 5).Font.Bold = True Cells(i, 5).Font.Color = RGB(0,0,255) End If Next i To check for several conditions: If Cells(i, 5).Value > 5000 then Cells(i, 5).Font.Color = RGB(255,0,0) ElseIf Cells(i, 5).Value > 2500 then Cells(i, 5).Font.Color = RGB(0,0,255)

MrExcel.com

2014 MrExcel.com

Follow Bill Jelen on Twitter @MrExcel


Fair use: If you bought this PDF, print up to 10 copies with my compliments. Beyond that, buy a license to print more copies; $1 per 10 copies via PayPal to Karma@MrExcel.com. Need to make just 1 copy? Go ahead, but please tweet "#FF @MrExcel Thanks for the #Excel tips!"

$2.95 Print ISBN 978-1-61547-992-4 $1.00 PDF ISBN 978-1-61547-985-6

Você também pode gostar