如何从VB宏代码中退出Foreach语句?

时间:2013-06-26 12:09:49

标签: excel-vba vba excel

塞纳里奥: 嗨,我是宏编程新手......我需要比较不同工作簿中的两列,并复制其中一个工作簿中的不匹配值。

代码:

For Each y In CompareRange     
         For Each x In Selection       
            If x <> y Then temp = y       
                    intRowPosition = intRowPosition + 1
                      Next x
                      Workbooks("junk").Worksheets("sheet1").Range("C" & CStr(intRowPosition)).Value = temp
                      intRowPosition = intRowPosition - 5                           
              Next y

问题:

在上面的代码中(如果x&lt;&gt; y为false)我需要循环移动到Next Y, 请告诉我如何从foreach循环中退出。

3 个答案:

答案 0 :(得分:1)

第一个选项:如果你想执行X循环后的内容

For Each y In CompareRange     
    For Each x In Selection       
        If x <> y Then temp = y       
                intRowPosition = intRowPosition + 1
        Else
             Exit For
        End If
    Next x

    Workbooks("junk").Worksheets("sheet1").Range("C" & CStr(intRowPosition)).Value = temp
    intRowPosition = intRowPosition - 5                           
Next y

第二个选项:如果你不想执行X循环后的内容。

Dim CanExecute as Boolean    

For Each y In CompareRange    
    CanExecute = True

    For Each x In Selection       
        If x <> y Then temp = y       
                intRowPosition = intRowPosition + 1
        Else
            CanExecute = False
        End If
    Next x

    If CanExecute Then
        Workbooks("junk").Worksheets("sheet1").Range("C" & CStr(intRowPosition)).Value = temp
        'I'm not sure if this would be inside or outside the if, that's up to you.
        intRowPosition = intRowPosition - 5                           
    End If
Next y

答案 1 :(得分:-2)

您必须指定范围。这是一种方式。

 For Each y In Workbooks("junk").Worksheets("sheet1").Range("B5:B" & Rows.Count).End(xlUp).Row     
     For Each x In Workbooks("junk").Worksheets("sheet1").Range("C5:C" & Rows.Count).End(xlUp).Row            
        If x <> y Then temp = y       
        intRowPosition = intRowPosition + 1
     Next x
     Workbooks("junk").Worksheets("sheet1").Range("C" & CStr(intRowPosition)).Value = temp
     intRowPosition = intRowPosition - 5                           
  Next y

答案 2 :(得分:-2)

您可以在名称管理器中添加一个名称,然后将其链接回宏,请尝试查看它是否有效。

Dim CompareRange As Range
Set CompareRange = Range("compare_range")

For Each y In CompareRange
         For Each x In Selection
            If x <> y Then
            temp = y

                   intRowPosition = intRowPosition + 1
                      End If 'Added this in
                      Next x
                      Workbooks("junk1").Worksheets("Sheet1").Range("C" & CStr(intRowPosition)).Value = temp
                      intRowPosition = intRowPosition - 5
              Next y