VBA切割插入功能无法正常工作

时间:2013-07-02 19:47:17

标签: excel vba excel-vba range

如果它们在B列中包含“CL”,然后将剪切插入另一个工作表,我试图从一个范围中删除行。它正在做得很漂亮,但如果B列不包含“CL”,它会在电子表格中插入一个空行而不是什么都不做。我不确定为什么要插入空行?这是代码

With Sheets("Data")
    .Select
    ViewMode = ActiveWindow.View
    ActiveWindow.View = xlNormalView
    .DisplayPageBreaks = False
    Firstrow = .UsedRange.Cells(1).Row
    Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row
    For Lrow = Lastrow To Firstrow Step -1
        With .Cells(Lrow, "B")

            If Not IsError(.Value) Then

                    If .Value = "CL" Then .EntireRow.Cut
                        Sheets("Sheet1").Select
                        Rows("10:10").Select
                        Selection.Insert Shift:=xlDown

               End If

           End With

       Next Lrow

   End With

End Sub

1 个答案:

答案 0 :(得分:3)

只有当您点击CL时才进行EntireRow.Cut,但是您总是在进行插入(即使您没有找到CL)。

你的缩进使它看起来像你正在做切割,选择并有条件地插入所有,但事实上你使用单行if形式。在这种形式中,只有then到行尾之后的部分才是有条件的;后续行不是有条件的。

如果我更正你的缩进,那么这就是你所拥有的:

With .Cells(Lrow, "B")
    If Not IsError(.Value) Then
        If .Value = "CL" Then .EntireRow.Cut     '<--- this is a single-line if

        Sheets("Sheet1").Select                  '<--- this, and the next two lines, will always run if .Value is not an error value
        Rows("10:10").Select
        Selection.Insert Shift:=xlDown
    End If  
End With

尝试使用多行if

With .Cells(Lrow, "B")
    If Not IsError(.Value) Then
        If .Value = "CL" Then
            .EntireRow.Cut     '<--- everything from here to the "End If" will run when you hit a CL
            Sheets("Sheet1").Select
            Rows("10:10").Select
            Selection.Insert Shift:=xlDown
        End If
    End If
End With
相关问题