如何停止每个循环

我是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 

这就是我要的。

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

这是我得到的…

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

尝试

 if x=y then exit for 

此外,你想复制x,而不是select。

这是你的代码

  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 

当条件满足时,可以使用Exit For语句打破循环。