Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

combining for-loops 1

Status
Not open for further replies.

Luis939

MIS
Feb 28, 2003
453
US
Is there anyway to combine these 3 forloops

For Each sCell In Range(Cells(1, 4), Cells(5, 5))
If sCell.Formula Like "=+*" Then
PERFORM SAME INSTRUCTIONS
Next sCell

For Each sCell In Range(Cells(1, 7), Cells(5, 9))
If sCell.Formula Like "=+*" Then
PERFORM SAME INSTRUCTIONS
Next sCell

For Each sCell In Range(Cells(1, 11), Cells(5, 12))
If sCell.Formula Like "=+*" Then
PERFORM SAME INSTRUCTIONS
Next sCell

Basically so that instead of doing one region then the other and then the other, i just want it do everycell in columns 4 and 5 and then skip over to columns 7-9 and then 11-12 without using 3 different forloops thanks
 
There are a couple of ways to do this...
Personally I like to separate control structures from detail code, so I would probably do it this way:
[blue]
Code:
Sub test()
  Call PerformSomeInstructions("D1:E5")
  Call PerformSomeInstructions("G1:I5")
  Call PerformSomeInstructions("K1:L5")
End Sub

Sub PerformSomeInstructions(ARangeAddress As String)
Dim c As Range
  For Each c In Range(ARangeAddress)
    If c.Formula Like "=+*" Then
      MsgBox c.Address
    End If
  Next c
End Sub
[/color]


But if you prefer, you could also do it this way:
[blue]
Code:
Sub Perform2()
Dim r As Range
Dim c As Range
  Set r = Union(Range("D1:E5"), Range("G1:I5"), Range("K1:L5"))
  For Each c In r
    If c.Formula Like "=+*" Then
      MsgBox c.Address
   End If
  Next c
  Set r = Nothing
End Sub
[/color]

You pays your money and you takes your choice.

 
Interesting, Ive never used the Union statement before, but always wanted too lol thanks Zathras
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top