Basics of VBA / Macros Chapter – 25 (Loop Part‑2)

⚡ Macro Developer Toolkit

Copy or Export this Code to VBA

Use these verified developer utilities to run this lesson directly inside your Microsoft Excel Visual Basic Editor.

🖇 View Code Example
Basics of VBA / Macros Chapter – 25 (Loop Part-2)
⏱ 2 min readUpdated 12 November 2026

Loop through Defined Range

 Below we will look at a program that loops through a defined range. For example, when we want to square the numbers in Range(“A1:A3”). Did you know you can also loop through a dynamic range?

Situation:

Loop through Defined Range in Excel VBA

Place a command button on your worksheet and add the following code lines:

We will declare two Range objects. We call the Range objects rng and cell.

Dim rng As Range, cell As Range

We will initialise the Range object rng with Range(“A1:A3”).

Advertisement
Set rng = Range("A1:A3")

Add the For Each Next loop.

For Each cell In rng

Next cell

rng and cell are randomly chosen here, you can use any names. Remember to refer to these names in the rest of your code.

Next, we will square each cell in this range. To achieve this, add the following code line to the loop:

cell.Value = cell.Value * cell.Value

Result when you click the command button on the sheet:

Loop through Defined Range Result

If you want to check each cell in a randomly selected range, simply replace:

Advertisement
Set rng = Range("A1:A3")

with:

Set rng = Selection

6. Now, for example select Range(“A1:A2”).

Loop through Selection in Excel VBA

Result when you click the command button on the sheet:

Loop through Selection Result

✨ Ask AI about this article

Stuck on a step? Ask a question and the AI answers using this article.

Free · AI can be wrong