我有一個大約 20k 行和幾列的串列。其中一列包含注釋。下面的代碼遍歷串列的行,復制所有具有注釋“付款日期”的行,并將它們粘貼到另一個作業表中。
但回圈永遠不會結束。
問題是什么?
這是我的代碼:
Sheets("MASTER").Select
rowslength = Range("O" & Rows.Count).End(xlUp).Row
'MsgBox rowslength
Set keyword1 = Cells.Find(what:="Date of Payment")
For i = 1 To rowslength
keyword1.Select
Selection.EntireRow.Select
Selection.Copy
With Sheets("Date of Payment").Range("a" & Rows.Count).End(xlUp).Offset(1)
.PasteSpecial
End With
Sheets("MASTER").Select
Set keyword1 = Cells.FindNext(keyword1)
Application.CutCopyMode = False
Next i
uj5u.com熱心網友回復:
正如 Warcupine 在評論中所說,您正在從填充范圍的第一行回圈到最后一行。假設這是 20,000 行。但也許您只有 500 條符合您條件的評論。即使您復制了所有需要的資料,for 回圈仍將繼續處理另外 19,500 次迭代。您需要做的就是在進入 for 回圈之前存盤第一個匹配項,然后在每次互動時檢查下一個找到的單元格是否與第一個找到的單元格匹配。像這樣:
Sub test()
Sheets("MASTER").Select
rowslength = Range("O" & Rows.Count).End(xlUp).Row
'MsgBox rowslength
Set keyword1 = Cells.Find(what:="Date of Payment")
Set firstFoundCell = keyword1 'store the first found cell
For i = 1 To rowslength
keyword1.Select
Selection.EntireRow.Select
Selection.Copy
With Sheets("Date of Payment").Range("a" & Rows.Count).End(xlUp).Offset(1)
.PasteSpecial
End With
Sheets("MASTER").Select
Set keyword1 = Cells.FindNext(keyword1)
Application.CutCopyMode = False
If keyword1.Address = firstFoundCell.Address Then Exit For 'stop when back at the first cell
Next i
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/416888.html
標籤:
下一篇:撰寫此代碼的正確方法是什么?
