How to select and cut an entire row from sheet1 an

2019-09-14 18:52发布

Simple table in sheet1 with data in cells(A2:C4), column D is empty. I want to select the entire row, cut and paste it in sheet2 when a time is added in colum D. When I clicked on the logout button, It will add a time punch in column D. I want that entire row to be selected and then cut and paste in sheet2. I want also to arrange the remaining entry to move up so that there's no spaces between.

Screenshot

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

标签: excel vba
1条回答
淡お忘
2楼-- · 2019-09-14 19:35

You need to remove your loop, and just use the row you found using the 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

Note that Excel exhibits very odd behaviour when deleting the row after the Cut. Using a statement of myLogSheet.EntireRow.Delete after the Cut causes Excel to delete the row in Sheet1 based on the new location of the cell in Sheet2. This is why a variable needs to be created to refer to the row prior to the Cut, so that it can be used in the Delete after the Cut.

查看更多
登录 后发表回答