对于每个循环问题

时间:2016-05-13 12:23:54

标签: vba excel-vba excel

我有以下vba代码,适用于vba“For Each 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

2 个答案:

答案 0 :(得分:1)

如果您只想运行一次,请在Next olMail之前使用Exit For。如果要在满足if条件后退出,请将其置于End if

之前

试试这个:

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

答案 1 :(得分:0)

替换

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

使用

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
相关问题