Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

excel vba : selected cells loop

Tags:

excel

vba

Would like to iterate each row in a selection in excel VBA.

I have:

Dim rng As Range
Dim s As String
Set rng = Application.Selection
Debug.Print "c :" & rng.Address

This prints

c :$B$22:$C$29

How to make a loop from row 22 to 29/ parse out the start and end row?

And in separate int variables get the start and end column?

like image 957
tgkprog Avatar asked Feb 03 '14 11:02

tgkprog


People also ask

How do you loop through a range of cells?

One way to loop through a range is to use the For... Next loop with the Cells property. Using the Cells property, you can substitute the loop counter (or other variables or expressions) for the cell index numbers. In the following example, the variable counter is substituted for the row index.

What does RNG mean in VBA?

Random Number Generator in Excel / VBA.

How do you run a macro if a cell is selected?

Run Macro When a Cell Changes (Method 1) This works on a specific cell and is the easiest method to use. Go to the VBA Editor (Alt + F11) and double-click the name of the spreadsheet that contains the cell that will change or just right-click the worksheet tab and click View Code.


1 Answers

A general solution to looping through a range of cells in Excel:

Sub LoopSelection()

    Dim cel As Range
    Dim selectedRange As Range

    Set selectedRange = Application.Selection

    For Each cel In selectedRange.Cells
        Debug.Print cel.Address, cel.Value
    Next cel

End Sub

Iterates from top-left most cell, across then down.

like image 79
dspies Avatar answered Oct 21 '22 16:10

dspies