基于单元格内容剪切和粘贴行的宏仅工作一半-剪切单元格但未粘贴

时间:2019-07-11 09:01:03

标签: excel vba

当L列包含Complete或Held语句时,我正在运行一个宏,该宏用于在Open Actions上剪切和粘贴行的内容。

这两个语句均确定应将行剪切并粘贴到哪张纸上。

  • 如果L行的内容为“完成”,则移至“完成的操作”
  • 如果保留了L行的内容,请转到“暂停的操作”

表的内容要到第6行才开始,因为上面有标题和标题,与目的表的内容相同。

我似乎无法指定剪切和粘贴的单元格要填充到的特定行。

这是我到目前为止的代码的副本:

我尝试了多种VBA方法,但似乎找不到有效的方法。

Sub completeaction()

Set wsOne = ActiveWorkbook.Sheets("Open Actions")
Set wsTwo = ActiveWorkbook.Sheets("Completed Actions")
Set ws.Three = ActiveWorkbook.Sheets("Held Actions")

lastRow = wsOne.Cells(wsOne.Rows.Count, 1).End(xlUp).Row

MsgBox lastRow

For i = 1 To lastRow
    lastOutRow = wsTwo.Cells(wsTwo.Rows.Count, 1).End(xlUp).Row + 1
        If wsOne.Range("L" & i).Value = "Complete" Or wsOne.Range("L" & i).Value = "Held" Then
            wsTwo.Rows(lastOutRow).Value = wsOne.Rows(i).Value
            wsOne.Rows(i).EntireRow.Delete
        End If
Next

End Sub

此宏的预期结果是,根据行L中的说明,行将移至相应的工作表。

1 个答案:

答案 0 :(得分:0)

几件事。

  • 我认为您需要将If分为两个不同的条件 需要产生不同的结果;因此,您还需要一个变量 在两张纸的每一页中找到最后一行

  • 养成声明变量的习惯(使用Option Explicit)

  • 在删除行时,请向后循环以免跳过行

    Sub completeaction()
    
    Dim wsOne As Worksheet 'etc
    Dim lastRowOne As Long 'etc
    
    Set wsOne = ActiveWorkbook.Sheets("Open Actions")
    Set wsTwo = ActiveWorkbook.Sheets("Completed Actions")
    Set wsThree = ActiveWorkbook.Sheets("Held Actions")
    
    lastRowOne = wsOne.Cells(wsOne.Rows.Count, 1).End(xlUp).Row
    lastrowtwo = wsTwo.Cells(wsTwo.Rows.Count, 1).End(xlUp).Row + 1
    lastrowthree = wsThree.Cells(wsThree.Rows.Count, 1).End(xlUp).Row + 1
    
    For i = lastRowOne To 1 Step -1
        If wsOne.Range("L" & i).Value = "Complete" Then
            wsTwo.Rows(lastrowtwo).Value = wsOne.Rows(i).Value
            wsOne.Rows(i).EntireRow.Delete
            lastrowtwo = lastrowtwo + 1
         ElseIf wsOne.Range("L" & i).Value = "Held" Then
            wsThree.Rows(lastrowthree).Value = wsOne.Rows(i).Value
            wsOne.Rows(i).EntireRow.Delete
            lastrowthree = lastrowthree + 1
        End If
    Next
    
    End Sub