2015-12-02 98 views
2

请告诉我在我的下面的代码有什么问题。我能够切断并越过该行,但在此之后,我可以在我的工作表中看到空行。我们如何自动调整行。vba剪切和过去功能没有任何空白行

切割过去之后,原稿中不应有任何空白行。

Dim i As Variant 
endrow = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row 
For i = 2 To endrow 
If ws1.Cells(i, "M").Value = str Then 
ws1.Cells(i, "M").EntireRow.Cut Destination:=ws2.Range("A" & LastRow +).EndxlUp).Offset(1) 
End If 
Next 
+2

当您剪切和粘贴,就应该删除行,所以你的迭代将无法正常工作。用'step -1'试试你的循环' – Raystafarian

+1

同样交换你的'我'值'对于我= endrow到2步-1'。正如@Raystafarian建议的那样,该行被删除,这意味着下一行(它将变成'i'下一个)实际上会移动到您当前的'i'值,这意味着它会被忽略。 – bmgh1985

+0

正如其他人所说 - 你需要通过工作表反向工作。 **另外**切割一个值不会删除单元格 - 它会留下一个空白单元格(尝试手动执行)。切割后删除行 - 'ws1.Cells(i,“M”)。EntireRow.Delete Shift:= xlUp' –

回答

0

这将这样的伎俩:

Sub Test() 
    Dim i As Long 
    Dim endrow As Long 

    'Added this code to get it working on my test file. 
    Dim ws1 As Worksheet 
    Dim ws2 As Worksheet 
    Dim str As String 
    Dim lastrow As Long 
    Set ws1 = ThisWorkbook.Worksheets("Sheet1") 
    Set ws2 = ThisWorkbook.Worksheets("Sheet2") 
    str = "DELETE THIS ROW" 
    lastrow = 30 
    '''''''''''''''''''''' 

    endrow = ws1.Range("A" & ws1.Rows.Count).End(xlUp).Row 
    For i = endrow To 2 Step -1 
    If ws1.Cells(i, "M").Value = str Then 
     ws1.Cells(i, "M").EntireRow.Cut Destination:=ws2.Range("A" & lastrow).End(xlUp).Offset(1) 
     ws1.Cells(i, "M").EntireRow.Delete Shift:=xlUp 
    End If 
    Next 
End Sub