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