You Usually Don’t Need to Select an Object in Excel VBA

When you record VBA macros, Excel records each item you select. Here's why and how to avoid selecting those objects in your actual macro.

4188

When you record VBA macros, Excel records each item you select. Here's why and how to avoid selecting those objects in your actual macro.An Excel VBA user asked in a forum recently how to select a sheet in VBA when the sheet name is stored as a variable. The odds are about 95% that he didn’t need to select the worksheet in the first place.

To illustrate, I turned on my macro recorder, selected cell D9, and entered “x” in the cell. Here’s how Excel recorded the macro:

Sub Macro1()
   Range("D9").Select
   ActiveCell.FormulaR1C1 = "x"
End Sub

Excel had to record this macro in two steps because I really did (1) select cell D9, and then I did (2) enter a value into that cell. But in your VBA programs, you seldom need to select an object (like a worksheet, a range, a chart, or whatever) in order to do something with that object. Instead, you can specify the object and then apply the action directly.

To illustrate, this macro enters “x” in the workbook, worksheet, and cell shown, without activating Book1, Sheet1, or cell D9:

Sub Macro2()
   Workbooks("Book1").Worksheets("Sheet1").Range("D9").FormulaR1C1 = "x"
End Sub

Similarly, you could perform two actions, like this:

Sub Macro3()
   With Workbooks("Book1").Worksheets("Sheet1").Range("D9")
      .FormulaR1C1 = "x"
      .Font.Bold = True
   End With
End Sub

There are at least two advantages to writing code that doesn’t select the objects you’re working with. First, your code will work a lot faster. Second, it will be shorter and easier to write.

Previous articleWhat’s a ‘Deprecated’ Function in Excel?
Next articleThe First Excel Dashboard Report
Charley Kyd
Early in my career, I worked nearly 20 years as the CFO of turnarounds and startups. But I eventually got burned out fighting continual struggles with cash flow. That's when I started to write about Lotus 1-2-3, the spreadsheet software that I'd been using most of the time during the CFO days. When Excel was about to be introduced for the PC, one of my magazine editors set up a meeting for me to see the product, talk with the developers, and write a cover story about Excel. So I used the first version of Excel before it was launched. And I had also used the first version of VisiCalc before it was launched. And then,