如何从sheet1中选择并剪切整行并将其粘贴到sheet2中

时间:2017-06-14 23:49:06

标签: excel vba

sheet1中的简单表,单元格中的数据(A2:C4),列D为空。我想选择整行,在colum D中添加时间时将其剪切并粘贴到sheet2中。 当我点击退出按钮时,它会在D列中添加时间戳。 我希望选择整行,然后剪切并粘贴到sheet2中。 我还想安排剩余的条目向上移动,以便之间没有空格。

截图

Screenshot

Dim CM As Boolean

Private Sub cmdMove_Click()

Dim myLog As Worksheet
Dim myLogSheet As Range
Dim i As Long: i = 1

Set myLog = Sheets("Sheet1")
Set myLogSheet = myLog.Range("B:B").Find(txtID.Value, , , xlWhole)

'Dim LastRow As Long
'LastRow = Sheets("Sheet2").Range("A65536").End(xlUp).Row + 1
If Not myLogSheet Is Nothing Then
myLogSheet.Offset(0, 2) = Format(Now, "hh:mm:ss")

With ActiveSheet
For n = nLastRow To nFirstRow Step -1
        If .Cells(n, "D") = "" Then
            .Cells(n, "D").EntireRow.Cut Sheet2.Cells(i, "A")
            .Cells(n, "D").EntireRow.Delete '~~> if you want to delete
            i = i + 1
        End If
    Next
End With


Else
txtName.Value = "NO RECORD"

End If


End Sub

1 个答案:

答案 0 :(得分:0)

您需要移除循环,只需使用Find找到的行:

Dim CM As Boolean

Private Sub cmdMove_Click()

    Dim myLog As Worksheet
    Dim myLogSheet As Range
    Dim myLogSheetRow As Long
    Dim i As Long
    i = 1
    'Probably you want:
    i = Sheet2.Cells(Sheet2.Rows.Count, "A").End(xlUp).Row + 1

    Set myLog = Sheets("Sheet1")
    Set myLogSheet = myLog.Range("B:B").Find(txtID.Value, , , xlWhole)

    If Not myLogSheet Is Nothing Then
        myLogSheetRow = myLogSheet.Row ' So we can delete the row later
        myLogSheet.Offset(0, 2) = Format(Now, "hh:mm:ss")
        myLogSheet.EntireRow.Cut Sheet2.Cells(i, "A")
        myLog.Rows(myLogSheetRow).Delete
    Else
        txtName.Value = "NO RECORD"
    End If
End Sub

请注意,在Cut之后删除行时,Excel会表现出非常奇怪的行为。在myLogSheet.EntireRow.Delete之后使用Cut语句导致Excel根据Sheet2 中单元格的新位置删除Sheet1 中的行。这就是为什么需要创建变量以引用Cut之前的行的原因,以便可以在Delete之后的Cut中使用它。