如果不是“”,在VBA的最后一行之后粘贴

我在那里我有以下问题:如果结果不是“不匹配”,我想将结果粘贴到新工作表中,如何将其粘贴到新工作表中,最后一次使用的行之后? 我在Active.Paste上遇到错误

这是我的代码:

Public Sub CopyRows() Sheets("Koppeling data").Select ' Find the last row of data FinalRow = Cells(Rows.Count, 4).End(xlUp).Row ' Loop through each row For x = 3 To 10 ' Decide if to copy based on column D ThisValue = Cells(x, 4).Value If ThisValue = "NO MATCH" Then Else Rows(x).Copy Sheets("All sessions").Select Call FindingLastRow ActiveSheet.Paste Sheets("Koppeling data").Select End If Next x End Sub Sub FindingLastRow() Dim sht As Worksheet Dim LastRow As Long Set sht = ThisWorkbook.Worksheets("All sessions") LastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row End Sub 

给这个一个镜头。 我简化了代码,删除了.Select语句(应该不惜一切代价避免) ,并将variables赋值给对象,并直接与它们一起工作。

 Public Sub CopyRows() Dim wsK As Worksheet, wsA As Worksheet Set wsK = Sheets("Koppeling data") Set wsA = Sheets("All sessions") Dim FinalRow as Long FinalRow = wsk.Cells(wsk.Rows.Count, 4).End(xlUp).Row ' Loop through each row in Koppeling data For x = 3 To FinalRow ' Decide if to copy based on column D If wsK.Cells(x, 4).Value <> "NO MATCH" Then wsK.Rows(x).EntireRow.Copy _ Destination:=wsA.Range("A" & wsA.Rows.Count).End(xlUp).Offset(1) 'used `.Offset(1)` here so it will paste one row below last row with data. 'use this to paste values 'wsk.Rows(x).Copy 'wsA.Range("A" & wsA.Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues End If Next x End Sub 

你有FindingLastRow作为子,它没有做任何事情。 如果你想返回结果(在你的情况下最后一行),你必须定义它作为一个函数:

 Function FindingLastRow() as Long 'Your existing code FindingLastRow = LastRow End Function 

这将返回最后一行的值,并在主分区,你可以粘贴到以下行:

 Dim lastRow as Long lastRow = FindingLastRow ActiveSheet.Range("A" & lastRow + 1).Paste 

尝试摆脱使用Worksheet.Select和范围 。select完成您的操作。

 Public Sub CopyRows() Dim x As Long, lastRow As Long, finalRow As Long With Worksheets("Koppeling data") ' Find the last row of data finalRow = .Cells(.Rows.Count, 4).End(xlUp).Row ' Loop through each row For x = 3 To 10 'For x = 3 To finalRow ' Decide if to copy based on column D If UCase(.Cells(x, 4).Value) <> "NO MATCH" Then FindingLastRow Worksheets("All sessions"), lastRow .Rows(x).Copy Destination:=Worksheets("All sessions").Range("A" & lastRow + 1) End If Next x End With End Sub Sub FindingLastRow(ws As Worksheet, ByRef lr As Long) With ws lr = .Cells(.Rows.Count, "A").End(xlUp).Row End With End Sub 

ByRef允许你将一个先前声明的variables传递给你的帮助子,并让这个variables返回一个变化的值。


请参阅如何避免使用在Excel VBAmacros中select更多的方法来摆脱依靠select和激活来实现您的目标。