Excel VBA调试:循环不搜索整个范围

时间:2013-11-06 15:15:08

标签: excel vba loops excel-vba copy-paste

我写了一个基本宏来搜索范围(在一张纸上),然后根据包含选择值的第三张纸将所选单元格复制到另一张纸张。我已经使用了循环i = x到y bu它看起来像宏正在跳过一些行!???! 即,如果要在行1到4上复制4个有效值,则宏仅复制第2行和第4行的值(丢弃有效单元1和3)。这是代码:

Sub XXXXX()
Dim i As Integer
Dim PasteSheet As Worksheet: Set PasteSheet = Sheets("Sheet1")
Dim CopySheet As Worksheet: Set CopySheet = Sheets("Sheet2")
Dim SearchSheet As Worksheet: Set SearchSheet = Sheets("Sheet3")
Dim LookupID, LookupID_SearchRange, CopyValueID, CopyValueID_Paste As Range

For i = 7 To 2000 'I've also used the (Step 1) option with no success
RowCount = Application.WorksheetFunction.CountA(PasteSheet.Range("A:A")) + 1 'finds the last cell to be used for copy

Set LookupID = CopySheet.Range("A" & i) 'searches all values within column A from row 7 to 2000
Set LookupID_SearchRange = SearchSheet.Range("A:A") ' Seaches if the values from Sheet3 are present in Sheet 1
Set CopyValueID = CopySheet.Range("X" & i) 'counter that follows the same search on A but selects values on X
Set CopyValueID_Paste = PasteSheet.Range("A" & RowCount) 'When it finds the ID, it copies some cell to the last row in Sheet2
      ' Initially  there was an additional RowCount (+1) for CopyValueID. Corrected based on answers for future refrence of the cleaned code.
If Not IsError(Application.Match(LookupID, LookupID_SearchRange, 0)) Then
    If CopyValueID.Value <> "" Then
        CopyValueID.Copy
        CopyValueID_Paste.PasteSpecial xlPasteValues
    End If
End If
Next i

End Sub

为什么代码会从第2行和第4行中选择和复制值(它会像使用+1步一样接缝?) 感谢。

2 个答案:

答案 0 :(得分:3)

您将RowCount定义为CountA + 1

RowCount = Application.WorksheetFunction.CountA(PasteSheet.Range("A:A")) + 1 'finds the last cell to be used for copy

然后你实际上在你粘贴的行中再添加一个:

Set CopyValueID_Paste = PasteSheet.Range("A" & RowCount + 1) ' When it finds the ID, it copies some cell to the last row in Sheet2

我认为你因此覆盖了你的结果?删除其中一个+1应该可以解决问题。

编辑:很高兴看到有人定义他们复制的范围,而不是使用一堆Select的......绝对是更好的编码风格!

答案 1 :(得分:2)

我认为您在两个地方向RowCount添加了+1

...
RowCount = Application.WorksheetFunction.CountA(PasteSheet.Range("A:A")) + 1
...
Set CopyValueID_Paste = PasteSheet.Range("A" & RowCount + 1) '<-- Remove the +1 here

其他一些注释 - 整体代码很好--------------------------

  • 正如评论中所指出的,找到RowCount有一个非常商定的最佳做法:RowCount = Range("A" & .Rows.Count).End(xlUp).Row + 1。这将解决列中可能出现空白单元格的问题,这会使COUNTA失效。

  • 您可以在不使用CopyValueID_PASTE.value = CopyValueID.Value的COPY和PASTE的情况下执行此操作。如果你在很多行上这样做,它将产生巨大的效率差异。