To loop through the cells a user has selected in Excel, assign Selection to a Range variable and use a For Each loop. The macro below prints each selected cell’s address and value in the VBA Immediate window; select worksheet cells before running it.
Save a copy of your workbook before running any macro that changes data: VBA actions generally cannot be reversed with Ctrl+Z. This example only reads cells and prints information, but a working copy is still a sensible precaution when trying unfamiliar code.
Sub InspectSelectedCells()
Dim selectedRange As Range
Dim cell As Range
' Stop if the current selection is not a worksheet range.
If TypeName(Selection) <> "Range" Then
MsgBox "Select worksheet cells first.", vbInformation
Exit Sub
End If
Set selectedRange = Selection
' Print each selected cell's address and value.
For Each cell In selectedRange.Cells
Debug.Print cell.Address(External:=True), cell.Value
Next cell
End Sub
To use it in Excel for Microsoft 365 on Windows, press Alt+F11 to open the Visual Basic Editor, choose Insert > Module, and paste the code into the module. Return to the worksheet, select cells, and press Alt+F8 to choose InspectSelectedCells and run it. In the Visual Basic Editor, press Ctrl+G to show the Immediate window. On Mac, Option+F11 may open the editor; some keyboards require Fn as well. Excel for the web cannot run or edit VBA macros, so use desktop Excel.
What “loop selected cells” means
In Excel VBA, Selection is the object currently selected in the user interface. When worksheet cells are selected, it usually refers to a Range object. A loop visits the cells in that range one by one, letting your code inspect a value, test a condition, or make a change to each cell.
The key distinction is between the current selection and a range your macro identifies itself. Selection depends on what the user clicked immediately before running the macro. By contrast, a reference such as Worksheets("Data").Range("A1:A10") always points to the specified cells. Selection-based macros are handy for user-directed tasks, while fixed range references are usually more predictable for repeatable processes.
The sample uses For Each cell In selectedRange.Cells rather than a numeric counter. Each pass gives the variable cell a reference to one cell, so you can use properties such as cell.Value, cell.Address, and cell.Interior.Color. The Immediate window is a convenient place to inspect results without writing anything into the sheet.
How to run and adapt the basic loop
After the macro runs, the Immediate window displays an address and the cell’s current value for each cell in the selection. The address includes the workbook and worksheet because the code uses External:=True. If you prefer a shorter address such as A1, change that expression to cell.Address(False, False). The second argument suppresses the dollar signs for absolute row and column references.
To adapt the loop, put the action you want to perform inside the loop, after any checks the task requires. For example, you can test whether a cell is blank before processing it, or compare its value with a target. Keep the action narrow and explicit: a statement that writes to cell.Value changes the worksheet, while a statement that reads cell.Value does not.
- Inspect values: read
cell.Valueorcell.Value2and send the result to the Immediate window or another output destination. - Check formulas: use
cell.HasFormulato distinguish formula cells from cells containing typed values. - Change formatting: set a property such as
cell.Interior.Color, taking care not to overwrite formatting unintentionally. - Change contents: assign a new value to
cell.Valueonly when replacing the selected cells is intended.
For one-time user-driven work, this pattern can be easier than building a macro around a fixed address. For a macro that others will run repeatedly, consider telling the user what to select and validating the selection before doing anything consequential.
Selections with multiple separate areas
A selection does not have to be one rectangular block. Users can select non-adjacent cells or ranges, for example by holding Ctrl while selecting on Windows. Such a selection is a multi-area range, and VBA exposes its separate parts through the range’s Areas collection. A loop over selectedRange.Cells can visit the cells in that selection, but code that needs to treat each separate block as a unit can make the areas explicit.
This pattern is useful when you need to calculate something separately for each selected block, or when you want the code to make the range structure clear:
Sub InspectSelectedAreas()
Dim selectedRange As Range
Dim area As Range
Dim cell As Range
' Check that worksheet cells are selected.
If TypeName(Selection) <> "Range" Then
MsgBox "Select worksheet cells first.", vbInformation
Exit Sub
End If
Set selectedRange = Selection
' Visit each separate block, then each cell in that block.
For Each area In selectedRange.Areas
Debug.Print "Area: " & area.Address
For Each cell In area.Cells
Debug.Print cell.Address, cell.Value
Next cell
Next area
End Sub
Do not assume that a multi-area selection behaves like one continuous rectangle. For example, operations that expect a single block may not produce the result you want when the selection contains gaps. If your task depends on processing order, define that order in your own logic rather than relying on an assumed order for separate areas.
Selection, ActiveCell, and fixed ranges
ActiveCell means the active cell within the current selection, not every selected cell. If a user selects A1:C5, for example, ActiveCell refers to one cell in that selection. A loop using only ActiveCell will not automatically visit the other 14 cells. Use a range loop when the task applies to all selected cells.
It is also possible to move around the sheet with ActiveCell.Offset, but that approach can make code harder to follow and may depend on where the selection starts. A For Each loop over a stored range makes the target explicit. If the macro should always process a known table or column, refer to that range directly instead of relying on the user’s selection.
Another practical distinction is that selection can be something other than cells. A chart, shape, or other object may be selected when the macro starts. That is why the example checks TypeName(Selection) before assigning it to a Range. Without a check, a macro may fail when it tries to use a range property on a non-range selection. The check provides a clear message and exits cleanly.
Common problems and safer choices
One common surprise is selecting an entire row or column. A worksheet column contains more than a million rows, so looping through every cell in a whole-column selection can take far longer than looping through a short data range. Select only the cells the task needs, or have the macro identify the relevant data area deliberately.
Other points to check before adding code that changes cells include:
- Blank cells: an empty cell and a formula that displays an empty string are not necessarily the same. Decide whether the macro should skip both, and test accordingly.
- Errors in cells: a cell can contain an Excel error value. If your code performs text or numeric operations on values, account for errors rather than assuming every value is ordinary text or a number.
- Filtered or hidden rows: a selection may include cells in hidden rows. A normal loop over the selected range does not automatically mean “visible cells only.”
- Merged cells: a merged block can complicate cell-by-cell logic because the displayed value is associated with the upper-left cell of the merged area.
- Undo: Excel’s normal undo history does not reverse most VBA changes. Test edits on a copy and keep a backup before running a write-enabled macro.
If you need visible cells only, investigate the range’s SpecialCells(xlCellTypeVisible) method. It can be useful with filtered lists, but it may raise an error when there are no matching visible cells, so robust code needs to handle that possibility. Also decide whether “visible” should include cells hidden manually as well as rows hidden by a filter.
Reading values versus changing cells
The example reads cell values and writes them to the Immediate window; it does not change worksheet contents. This is a good first step when learning what a selection contains. Value returns a cell’s value, while Value2 is often used when code wants the underlying value without VBA’s Currency and Date data-type conversions. For basic inspection, either may be suitable, but the choice can matter in code that depends on data types.
When a macro edits a cell, the effect is immediate. For instance, assigning a new value to cell.Value replaces the existing value or formula in that cell. Formatting changes also take effect immediately. If a macro must preserve original values, write results to a different range or store the original data before making changes. Consider first testing on a small selection and checking the result before expanding the task to a larger range.
For large selections, repeatedly reading or writing individual cells can be slower than transferring values as an array and processing that array in memory. That optimization is useful for large data sets, but it introduces extra details about array dimensions and writing results back. A cell-by-cell loop is often easier to understand for modest selections, especially when the operation involves different formatting or logic for each cell.
Macros, workbook files, and platform limits
To keep VBA code in a workbook, save it in a macro-enabled format such as .xlsm. A standard .xlsx workbook does not store VBA project code when saved. Excel may also display a security warning for macros; only run code from a source you trust, and follow your organization’s security rules rather than enabling all macros indiscriminately.
Excel for the web does not run VBA. Open the workbook in desktop Excel to use the Visual Basic Editor and run this kind of macro. The Windows shortcuts in the setup instructions are common defaults. On Mac, keyboard shortcuts can differ with the keyboard and system settings; use the Developer tab’s Macros command if a shortcut does not work. The VBA approach is broadly similar, though interface details and some platform-specific features can vary.
Frequently Asked Questions
How do I loop through every selected cell in Excel VBA? Assign the range selection to a Range variable, then use For Each cell In selectedRange.Cells. Check that the selection is a range first, because users can select objects as well as cells.
Does Selection include all cells in a multi-area selection? A range selection can contain several separate areas. You can loop through its cells, or loop through selectedRange.Areas and then through each area’s cells when you need to handle blocks separately.
How can I skip blank selected cells? Add a condition inside the loop before the action, such as checking IsEmpty(cell.Value). Note that a formula returning an empty string is different from a truly empty cell, so choose a test that matches your data.
Why does my macro fail when I select a chart? In that situation, Selection is a chart or another object rather than a worksheet Range. Check the selection type and exit with a useful message before using range properties.
Can I run a VBA loop in Excel for the web? No. Excel for the web does not run VBA macros. Open the file in desktop Excel for Windows or Mac to use the VBA Editor and run the macro.
Choosing the right loop for the task
Use a loop over Selection when the user should decide which cells to process at run time, and validate the selection before acting on it. Use a fixed range reference when the target is always the same, and use explicit area handling when a selection can contain separate blocks. Start with a read-only loop to confirm what will be processed; then add narrowly scoped edits only after checking the results on a saved copy.
Related
- How to Make Cell Borders White in Microsoft Excel 365
- How to Make a Number Superscript in Excel
- How to Make a Number Negative in Excel: Three Methods
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- Add Comments in Excel VBA: Notes and Threaded CommentsTo add a cell note with Excel VBA, select the cell and run ActiveCell.AddComment "Check this value." in…
- Excel VBA JSON: Parse, Read, and Write DataExcel VBA can work with JSON, but VBA has no built-in JSON parser. In desktop Excel, the usual…
- VBA Range Variables: How to Declare and Use ThemA VBA Range variable is an object variable that refers to one or more cells in an Excel…
- VBA Loop Through Worksheets: Examples and TipsTo loop through every worksheet in an Excel workbook, declare a Worksheet variable and use For Each ws…
- VBA Loop Through a Dictionary: Keys, Items, and ExamplesTo loop through a VBA Dictionary, use For Each key In dict.Keys, then read each value with dict(key).…
- Excel VBA Shortcut: Open the Editor and Run MacrosIn Excel for Windows, press Alt+F11 to open the Visual Basic Editor (VBE), where you can view and…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.