In VBA, “Selection” refers to the currently selected object in the active workbook—most commonly a cell, a range of cells, or a shape. To select cells or ranges in VBA, you use the Select method on a Range object, or you can use the Selection property to return the current selection. For example, Range("A1").Select selects cell A1, and Range("A1:B10").Select selects a block of cells. However, selecting is often unnecessary and can slow down your code; you can usually work directly with a range without selecting it first.
What Is Selection in VBA?
In Excel’s object model, Selection is a property of the Application object (and also of the Window object). It returns an object that represents whatever is currently selected in the active window. This could be a Range, a Chart, a Shape, a Worksheet (if you click a sheet tab), or even a PivotTable. The type of object returned depends on what the user has selected at the moment the code runs.
Because Selection can be many different object types, you often need to check its type before using it. For example, if you try to access Selection.Value when a chart is selected, you’ll get a runtime error. A common pattern is to use TypeName(Selection) or the TypeOf operator to verify it’s a range.
How to Select Cells and Ranges
The most straightforward way to select a cell or range is to use the Select method on a Range object. Here are the basic syntax examples:
' Select a single cell
Range("A1").Select
' Select a contiguous range
Range("A1:C10").Select
' Select a non-contiguous range (multiple areas)
Range("A1:A5, C1:C5").Select
' Select an entire row or column
Rows("3").Select
Columns("B").Select
' Select a range using variables
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Data")
ws.Range("A1").Select
Before you select anything, you must activate the worksheet that contains the range. If the sheet is not active, the Select method will fail. Use Worksheet.Activate first, or use a fully qualified range like ThisWorkbook.Sheets("Data").Range("A1").Select—but even then, the sheet must be active. A safer approach is to activate the sheet first:
Sheets("Data").Activate
Range("A1").Select
Why Avoid Selecting Whenever Possible
Selecting is a common habit for beginners because the macro recorder uses Select constantly. However, selecting is slow and can cause errors. When you select a range, Excel must update the user interface, scroll to the range, and change the active cell. This adds overhead and can make your macro run noticeably slower, especially if you select many ranges in a loop.
More importantly, selecting changes the state of the workbook. If your macro selects a range and then the user clicks elsewhere, your code may break. Also, if you rely on Selection to refer to a specific range, the code will fail if the user selects something else while the macro runs.
The best practice is to work directly with Range objects without selecting. For example, to set a value, you don’t need to select first:
' Instead of:
Range("A1").Select
Selection.Value = 10
' Do this:
Range("A1").Value = 10
This is faster, cleaner, and less error-prone. You can also use variables to refer to ranges:
Dim rng As Range
Set rng = Range("A1:B10")
rng.Font.Bold = True
Using the Selection Property in Macros
Sometimes you genuinely need to work with whatever the user has selected. For example, a macro that formats the selected cells. In that case, you can use the Selection property. Here’s a typical pattern:
Sub FormatSelection()
If TypeName(Selection) = "Range" Then
With Selection
.Font.Bold = True
.Interior.Color = RGB(255, 255, 0)
End With
Else
MsgBox "Please select a range of cells first."
End If
End Sub
Notice the TypeName check. This prevents errors if the user selected a chart or a shape. Another common check is If TypeOf Selection Is Excel.Range Then.
You can also get the address of the selection, count the cells, or loop through each cell in the selection:
Sub ShowSelectionInfo()
If TypeName(Selection) = "Range" Then
Dim cell As Range
For Each cell In Selection
Debug.Print cell.Address & ": " & cell.Value
Next cell
End If
End Sub
Selecting Rows, Columns, and Special Cells
Beyond simple ranges, you can select entire rows, columns, or special cells like the last used cell or cells with constants. Here are some examples:
- Entire row or column:
Rows("3").SelectorColumns("B").Select - Used range:
ActiveSheet.UsedRange.Select - Last cell in a column:
Range("A" & Rows.Count).End(xlUp).Select - Special cells (constants, blanks, etc.):
Range("A1:C10").SpecialCells(xlCellTypeConstants).Select - Current region (contiguous block of data):
Range("A1").CurrentRegion.Select
Note that SpecialCells can throw an error if no cells match the criteria, so you might want to use On Error Resume Next or check for Nothing.
Common Problems and Pitfalls
Several issues arise frequently when working with selection in VBA:
- Selecting a range on an inactive sheet: You must activate the sheet first, otherwise you get a runtime error 1004.
- Selection is not a Range: If the user has a chart or shape selected,
Selection.Valuewill fail. Always check the type. - Selecting a range on a different workbook: The workbook must be active. Use
Workbooks("Book1.xlsx").Activatefirst. - Selecting a range on a protected sheet: If the sheet is protected, selecting may be allowed but modifying may not. Ensure the sheet is unprotected or the macro is allowed to modify.
- Selecting a range when the worksheet is hidden: You cannot select a range on a hidden sheet. Unhide it first or use
Visible = xlSheetVisible.
Another common mistake is using Select in a loop, which is extremely slow. Instead, read the range into an array, process it, and write it back.
Alternatives to Selecting: Direct Range References
Instead of selecting, you can often use direct range references. This makes your code faster and more reliable. Here are some alternatives:
- Set values:
Range("A1").Value = 5instead of selecting and usingSelection.Value. - Format cells:
Range("A1:A10").Font.Bold = Trueworks without selecting. - Copy and paste: Use
Range("A1").Copy Destination:=Range("B1")instead of selecting and usingActiveSheet.Paste. - Loop through cells:
For Each cell In Range("A1:A10")works without selecting.
If you need to perform an action on the selection, you can store the selection in a variable at the start of the macro:
Dim myRange As Range
If TypeName(Selection) = "Range" Then
Set myRange = Selection
' Now you can use myRange even if the selection changes later
End If
Frequently Asked Questions
Do I always need to select a cell before changing its value?
No. You can directly assign a value to a range without selecting it: Range("A1").Value = 10. Selecting is only necessary if you want to visually highlight the cell or when you are using the macro recorder (which generates selecting code). In most cases, direct references are better.
Why does my macro fail with “Select method of Range class failed”?
This error usually occurs because the worksheet containing the range is not active. You must activate the sheet first: Sheets("Sheet1").Activate before using Select. Also, if the workbook is not active, you need to activate it first. Another cause is trying to select a range on a hidden or protected sheet.
How do I select all cells in a worksheet?
You can select all cells using Cells.Select (which selects the entire worksheet) or ActiveSheet.UsedRange.Select to select only the used range. Be careful with Cells.Select because it selects the entire sheet, which might be huge and cause performance issues.
What is the difference between ActiveCell and Selection?
ActiveCell is the single cell that is currently active (the one with the dark border). Selection can be a range of multiple cells, or even a non-range object. If you select a range of cells, ActiveCell is only the top-left cell of that selection.
Can I use Selection to refer to a shape or chart?
Yes, Selection can return a Shape or Chart object if such an object is selected. You can check the type with TypeName(Selection) and then access properties specific to that object. For example, if a shape is selected, Selection.Name gives the shape name.
Is it possible to select a range without activating the worksheet?
No, the Select method requires the worksheet to be active. However, you can still work with ranges on inactive sheets by using direct references, like Sheets("Sheet2").Range("A1").Value = 5. This works without activating the sheet.
Best Practices and Performance Tips
To write efficient and reliable VBA code, follow these guidelines:
- Avoid using Select unless absolutely necessary. Direct references are faster and less error-prone.
- Use variables to store ranges. This makes code easier to read and maintain.
- Check the type of Selection before using it. Use
TypeNameorTypeOfto avoid errors. - Activate the correct sheet before selecting. If you must select, ensure the target sheet is active.
- Save a copy of your workbook before running macros that select or modify cells. Macros cannot be undone with Ctrl+Z, so always keep a backup.
- Use
Application.ScreenUpdating = Falseto speed up macros that select many ranges. Remember to set it back toTrueat the end.
By understanding selection and knowing when to use it, you can write macros that are both powerful and robust.
Related
- Google Sheets Percentage of Total: Easy Formula
- Random Number Generator Between Two Numbers
- Auto Sum Shortcut in Excel: Quick Keys & Steps
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Excel VBA Progress Bar: How to Build a Responsive OneAn Excel VBA progress bar shows how much of a long-running macro has finished. For a visual bar,…
- Excel Analysis ToolPak vs ToolPak VBA: Key DifferencesExcel’s Analysis ToolPak is the add-in for running built-in statistical and engineering analyses from the Data tab; Analysis…
- VBA Pivot Table Fields: How to Manage ThemIn Excel VBA, a PivotTable’s fields are accessed through its PivotFields collection: set a field’s Orientation to place…
- VBA Sort Data in Excel: How to Build a Reliable MacroYes. In Excel for Microsoft 365 on Windows, VBA can sort a range or table by one or…
- Excel Data Macros: How They Work and When to Use ThemYes—an Excel macro can automate repetitive work on spreadsheet data, such as applying consistent formatting, checking entries, or…
- VBA Dictionary as a Public Constant? What Works in ExcelNo: a VBA Scripting.Dictionary cannot be declared as a Public Const, because VBA constants must hold compile-time values…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.