The difference between ActiveCell and Selection in Excel VBA and when to use them.
Both properties allow you to work with cells in a worksheet, but they operate in slightly different ways.
ActiveCell works only with a single cell, the currently active cell, which is the cell that text would be input into if you started typing while viewing the worksheet; this can be a single cell or the currently active cell in a range of selected cells - this can seem confusing so the examples below will illustrate this.
Selection works on every single cell that is selected by the user; this could be one cell or many cells at the same time.
Sub ActiveCell_Example()
ActiveCell.Value = "Hi!"
End Sub
This will input the value Hi! into the active cell.
User selects a single cell and runs the above macro:
User selects multiple cells and runs the macro:
Notice that in this example only one cell had a value input into it!
The cell that got the value is the cell that would have a value when you start typing from the keyboard.
The main thing to remember is that ActiveCell only works on a single cell.
User selects multiple cells that are not adjacent to one another.
Once again, only one cell gets a value.
In this case, the cell that is selected last will get the value.
Sub Selection_Example()
Selection.Value = "Hi!"
End Sub
This macro inputs the value Hi! into every single cell that the user has selected.
User selects a single cell and runs the macro:
User selects multiple cells in a range:
Every cell that was selected gets the value.
User selects multiple cells that are not adjacent to one another.
Once again, every cell that was selected gets the value.
It doesn't matter how the cells are selected or where they are, each selected cell is acted upon when you use the Selection property for VBA in macros in Excel
ActiveCell works on only 1 cell at a time.
Selection works on all cells that have been selected.
These properties allow you to do anything with the cell, not just input a value; for instance, you can use them to change the font, color, formulas, and any other thing related to a cell in Excel.
Download the sample file to work with these examples in Excel.