循环函数保持运行VBA Excel

我需要你的帮助来让我的代码工作。

我做了一个代码,将单元格的值从一个表单复制到另一个表单中,我需要在代码中循环来复制所有值,并在第一个值再次到达时停止。 到现在为止还挺好。

但是,当我改变代码来find其他的东西(例如“2 X”作为范围B)循环继续和粘贴在我的工作表的值,不能停止。

以下是可用的代码。

所以我需要一个相同的代码,但不同的条款,我希望你们可以帮助我。

Dim A As Range Sheet5.Activate Cells.Find(what:="1 X ", after:=ActiveCell, LookIn:=xlValues, lookat:=xlPart, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False , searchformat:=False).Copy ActiveCell.Select Set A = ActiveCell Sheet75.Activate row_number = row_number + 1 Cells(row_number, 2).Select ActiveCell.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=False Do Blad5.Activate Cells.FindNext(after:=ActiveCell).Select Cells.FindNext(after:=ActiveCell).Copy Sheet75.Activate row_number = row_number + 1 Cells(row_number, 2).Select ActiveCell.PasteSpecial Paste:=xlPasteValues, operation:=xlNone, skipblanks:=False, Transpose:=False Loop Until ActiveCell.Value = A.Value 

谢谢你,谢谢你的坏英文。

欢迎来到SO,请花一分钟时间参观: https : //stackoverflow.com/tour

我还强烈build议您阅读评论中分享的链接。


我改变了.Copy / .PasteSpecial ,这个速度很慢,而且你只想传送数值,这是一个更快的方法! ;)

以下是如何正确使用.Find方法:

 Sub test_Steelbox() Dim FirstAddress As String, _ cF As Range, _ LookUpValue As String, _ ShCopy As Worksheet, _ ShPaste As Worksheet, _ Row_Number As Double ''Setup here Row_Number = 2 LookUpValue = "2 X" Set ShCopy = ThisWorkbook.Sheets(Sheet5.Name) ''for example "data" Set ShPaste = ThisWorkbook.Sheets(Sheet75.Name) ''for example "summary" With ShCopy .Range("A1").Activate With .Cells ''First, define properly the Find method Set cF = .Find(What:=LookUpValue, _ After:=ActiveCell, _ LookIn:=xlValues, _ LookAt:=xlPart, _ SearchOrder:=xlByRows, _ SearchDirection:=xlNext, _ MatchCase:=False, _ SearchFormat:=False) ''If there is a result, do your data transfer and keep looking with FindNext method If Not cF Is Nothing Then FirstAddress = cF.Address Do ''This is much much faster than copy paste! ShPaste.Cells(Row_Number, 2).Value = cF.Value Row_Number = Row_Number + 1 Set cF = .FindNext(cF) ''Loop until you find again the first result Loop While Not cF Is Nothing And cF.Address <> FirstAddress End If End With End With End Sub