2

I Have below vba code which works with vba "For Each Loop". The problem is that I have used the below code in some other program, but in that the condition is same just I want to remove the loop thing in it.

The code should execute and stop after completing the task once. In short I want to remove the loop and do it in such a way where code runs without loop.

Set olNs = outlookApp.GetNamespace("MAPI")
Set Fldr = olNs.GetDefaultFolder(olFolderInbox)
Set myTasks = Fldr.Items

For Each olMail In myTasks
    If (InStr(1, olMail.Subject, ws.Range("E" & FinalRow), vbTextCompare) > 0) Then
        olMail.Display
    End If
Next olMail
1
  • Use Exit For just before Next olMail if you want torun it just once. If you want to exit after the if condition is met place it before End if. Commented May 13, 2016 at 12:31

2 Answers 2

1

Use Exit For just before Next olMail if you want to run it just once. If you want to exit after the if condition is met place it before End if

Try this:

For Each olMail In myTasks
    If (InStr(1, olMail.Subject, ws.Range("E" & FinalRow), vbTextCompare) > 0) Then
      olMail.Display
    Exit For
    End If
 Next olMail
Sign up to request clarification or add additional context in comments.

Comments

0

Replace

For Each olMail In myTasks
If (InStr(1, olMail.Subject, ws.Range("E" & FinalRow), vbTextCompare) > 0) Then
  olMail.Display
    End If
Next olMail

With

For Each olMail In myTasks
    If (InStr(1, olMail.Subject, ws.Range("E" & FinalRow), vbTextCompare) > 0) Then
        olMail.Display
        Exit For '// Exit the loop if the item is displayed.
    End If
Next olMail

5 Comments

This may not be exactly desired. I think OP wants to exit after the first match. myTasks(0) just tests it for that specific one.
@newguy the For loop will iterate over each item in the myTasks collection - which means the first 'match' or iteration will be the item at index 0. Therefore there is no need to use a loop at all, just access the first item in the collection directly.
@newguy nvm - I see what you mean, just re-read the question and updated.
Yes we don't know whether the 0th element will make the if condition true or not so we need the loop
@newguy When I first read the question, I thought the OP just didn't want to loop at all - hence the confusion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.