[VBA] For next require vs for each

montecarlo2012

Well-known Member
Joined
Jan 26, 2011
Messages
984
Office Version
  1. 2010
Platform
  1. Windows
Code:
Sub D_W()
      Dim X As Range, Y As Range
            For Each X In Range("B3:g3")
                  Set Y = Range("J5:Q10").Find(X, LookIn:=xlValues, lookat:=xlWhole)
                           If Not Y Is Nothing Then
                                     Y.Interior.ColorIndex = 6
                           End If
            Next X
End Sub
Hello, Hope a Great week for all.
Well, I am trying to replace this ►”FOR/EACH”◄ method, because I don’t see the possible way to control the ranges B:G and J:Q.

What I mean by this?
If I have for next statement I will be able to create two variables like [ X, Y] and just make:
x = Range(“A1”).value, and y = Range(“B1”).value,
so then my loop will be :

For m = x to y etc.

This is the kind of control I need in both ranges of the actual loop, but I don’t see how to do it with for/each statement.
“Any help is always appreciated”.
Thank you for reading this post.
 

Excel Facts

Bring active cell back into view
Start at A1 and select to A9999 while writing a formula, you can't see A1 anymore. Press Ctrl+Backspace to bring active cell into view.
Code:
Sub D_W()
Dim X As Range
Range("J5:Q10").Interior.Color = xlNone
For Each X In Range("B3:G3")
    Application.FindFormat.Clear
    With Application.ReplaceFormat.Interior
        .PatternColorIndex = xlAutomatic
        .ColorIndex = 6
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
   Range("J5:Q10").Replace What:=X, Replacement:=X, LookAt:=xlWhole, ReplaceFormat:=True
Next X
End Sub
 
Last edited:
Upvote 0

Forum statistics

Threads
1,214,606
Messages
6,120,490
Members
448,967
Latest member
visheshkotha

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top