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

时间:2016-03-02 15:26:12

标签: excel vba excel-vba paste

我存在以下问题:如果结果不是“NO MATCH”,我想将结果粘贴到新工作表中,如何将其粘贴到新工作表中以及最后一次使用的行之后?我在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

3 个答案:

答案 0 :(得分:2)

给它一个机会。我对代码进行了大量简化,删除了.Select语句 - 应该不惜一切代价避免使用,并将变量分配给对象并直接使用它们。

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

答案 1 :(得分:0)

你有FindingLastRow作为sub,它没有做任何事情。如果要返回结果(在您的情况下是最后一行),则必须将其定义为函数:

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

这将返回最后一行的值,并且在main子句中,您只需粘贴到以下行:

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

答案 2 :(得分:0)

尽量避免使用Worksheet.SelectRange .Select来完成您的操作。

system.peers

ByRef 允许您将先前声明的变量传递给助手子,并使该变量返回更改的值。

有关远离依赖选择和激活以实现目标的更多方法,请参阅How to avoid using Select in Excel VBA macros