VBA切割插入function无法正常工作

我试图削减行的范围,如果他们包含在列“B”,然后插入切到另一个工作表。 这是很好的做法,但如果列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 

只有当你点击一个CL,你才能完成EntireRow.Cut ,但是你总是插入(即使你没有find一个CL)。

你的缩进使得它看起来像你正在做的切割,select和有条件地插入,但实际上你正在使用单线如果forms。 在这种forms中,只有在通过行尾之后的部分是有条件的; 后续行不是有条件的。

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

 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