0

Senario:嗨,我是宏编程的新手……我需要比较来自不同工作簿的两列,并在其中一个工作簿中复制不匹配的值。

代码:

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 <> y 为假)我需要循环移动到下一个 Y,请让我知道如何摆脱 foreach 循环。

4

3 回答 3

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
于 2013-06-28T14:46:50.670 回答
-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
于 2013-06-26T13:25:28.247 回答
-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
于 2013-06-28T04:46:10.973 回答