[VBA] For next require vs for each

montecarlo2012

Active Member
Joined
Jan 26, 2011
Messages
364
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.
 

Some videos you may like

Excel Facts

Format cells as currency
Select range and press Ctrl+Shift+4 to format cells as currency. (Shift 4 is the $ sign).

footoo

Well-known Member
Joined
Sep 21, 2016
Messages
2,846
Office Version
2016
Platform
Windows
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:

Forum statistics

Threads
1,089,337
Messages
5,407,666
Members
403,158
Latest member
Limerick2030

This Week's Hot Topics

  • help please
    SORRY NOT ANY GOOD AT EXCEL SO HELP WOULD BE MUCH APPRECIATED this formula is in a sheet called ignore...
  • two formulas needed
    Hello, I'll try my best to explain this: First formula needed in Sheet1 cell A2: If Sheet1 cell B2 = Sheet2 cell B2 then return a 1. If not then...
  • Dynamic Counts
    Good afternoon, we are tidying up some data & the data seems to be growing quicker than we are tidying it up! What we confirm (by reviewing it...
  • Help Excel formula eliminate duplicate values and keep only 2 identical rows.
    as picture below column A has a duplicate value. but the values are not the same as the rule. sometimes 4 rows, sometimes 10 rows or 7 or 9...
  • Macro Compile Error Sub or Function not defined
    Hello, I am trying to run macros from a validation list, all macros have been created and run perfectly on there own but I'm getting a compile...
  • Last row combined with Current Region VBA
    I'm generally happy finding the last row of data through something like Lastrow = Cells(Rows.Count, "D").End(xlUp) but I don't always receive data...
Top