Frits Verstraten
Frits Verstraten

Reputation: 2179

Compile error when running a for loop over a range

I have the following code that tries to get a dynamic range and print the values of each cells of the range.

Sub Macro3()

'
    Range("D10").Select
    x = Range(Selection, Selection.End(xlDown)).Select


    For Each cell In x
        MsgBox (cell)
    Next x

End Sub

If I run it however it get a compile error... Any thoughts on what goes wrong here?

Upvotes: 0

Views: 59

Answers (2)

Vityata
Vityata

Reputation: 43575

Option Explicit

Sub Macro3()

    Dim x       As Range
    Dim cell    As Range


    Range("D10").Select

    Set x = Range(Selection, Selection.End(xlDown)).Select
    For Each cell In x
        MsgBox (cell)
    Next cell

End Sub

Hi. you need next cell and not next x. Enjoy! :D

Upvotes: 0

Fratyx
Fratyx

Reputation: 5797

Try this: (use Set and remove .Select)

Set x = Range(Selection, Selection.End(xlDown))

and Next or Next cell instead of Next x

Upvotes: 1

Related Questions