Stop For Each statement at first occurence

theclaah

New Member
Joined
Apr 26, 2002
Messages
29
How to I stop a For Each statment at the first occurence?
Or should I use a "find" somehow?
 

Excel Facts

How to calculate loan payments in Excel?
Use the PMT function: =PMT(5%/12,60,-25000) is for a $25,000 loan, 5% annual interest, 60 month loan.
Hi,

I take it you want to refer to the first item in the collection. For example, if you want to refer to the first worksheet in the worksheets collection just do this:-

Set MySheet = Worksheets(1)

This is the equivalent of doing this:-

For each w in Worksheets
Set MySheet=W
Exit For
Next
Msgbox Mysheet.name

HTH,
Dan
 
Upvote 0
Will actually I have a riange of data and I want to find the first occurence of a value less than zero.
 
Upvote 0
Try this:-

Code:
Sub FindLessThanZero()
Dim rngeCell As Range, rngeFound As Range

For Each rngeCell In Range("A1:A1329")
    If rngeCell.Value < 0 Then Set rngeFound = rngeCell: Exit For
Next rngeCell

If Not rngeFound Is Nothing Then
    MsgBox "The first cell with a value less than zero is " & rngeFound.Address
Else
    MsgBox "No cells were found in the specified range."
End If

End Sub

HTH,
Dan
 
Upvote 0

Forum statistics

Threads
1,214,825
Messages
6,121,788
Members
449,049
Latest member
greyangel23

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