如何停止每个循环

How to stop for each loop

我是 VBA 的新手。我正在尝试制作一个 for each 循环,它给我一个值的位置 x=y,但我一直在我的语句 (C10) 中获取最后一个 Y 的位置。我希望有一个人可以帮助我。 亲切的问候

Sub Find_Matches()
    Dim CompareRange As Variant, x As Variant, y As Variant
        Set CompareRange = Range("C1:C10")
        For Each x In Selection
        For Each y In CompareRange
            If x = y Then y.Select
    Application.CutCopyMode = False
    Selection.Copy
    x.Offset(0, 1).Select
    Selection.PasteSpecial Paste:=xlPasteFormats
    Selection.PasteSpecial Paste:=xlPasteValues
    x.Offset(0, 3).Value = y.Address

        Next y

   x.Offset(0, 5).Select



        Next x

End Sub

这就是我想要的。

A       B       C       D
1   1   5   $C
2       4   
3   3   6   $C
4   4   1   $C
5   5   9   $C
6   6   3   $C
7       75  
8       12  
9   9   55  $C
10      90  
11          
12  12      $C

这就是我得到的...

A       B       C       D
1   1   5   $C
2       4   $C
3   3   6   $C
4   4   1   $C
5   5   9   $C
6   6   3   $C
7       75  $C
8       12  $C
9   9   55  $C
10      90  $C
11          $C
12  12      $C

当条件满足时,您可以使用 Exit For 语句跳出循环。

尝试

if x=y then exit for

此外,您要复制 x,而不是所选内容。

这是您的代码

    Sub Find_Matches()

Range("A1:A12").Select

Dim CompareRange As Variant, x As Variant, y As Variant
Set CompareRange = Range("C1:C10")

For Each x In Selection

    For Each y In CompareRange

        If x = y Then

            Application.CutCopyMode = False
            x.Copy
            x.Offset(0, 1).PasteSpecial Paste:=xlPasteFormats
            x.Offset(0, 1).PasteSpecial Paste:=xlPasteValues
            x.Offset(0, 3).value = y.Address

        Exit For

        End If

    Next y

    x.Offset(0, 5).Select

Next x

End Sub