我编写了一个基本宏来搜索范围(在一张纸中),然后根据保存选择值的第三张纸复制所选单元格(到另一张纸)。我已经使用了 i = x to y 的循环,但看起来宏正在跳过一些行!???!
即,如果第 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 步骤?)
谢谢。
你正在定义RowCount
as 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
的......绝对是更好的编码风格!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)