Thursday, September 24, 2015

For Each

For Each variable In collection

Next variable

As the code for the For Each loop, For Each is used when you do something with Each item stored in that variable.


If you want to replace the space with hyphen and write the names in this way "John-Dow", For Each statement comes in handy.

Sub TestForEach()
Dim MyCell As Variant

For Each MyCell In Range("A1:A7")

    MyCell.Value = Replace(MyCell.Value, " ", "-")

Next MyCell

End Sub

The variable for For Each statement must be declared as variant. This For each statement replaces all spaces " " in the name with a hyphen "-". Names will be written with hyphens like John-Dow.