VBA嵌套做直到循环与每个循环

Do Until声明完美地工作; 但是,我不能继续超过第一个工作表。 预先感谢您的任何帮助。

Option Explicit Sub InsertBlankRow() Dim rowCount As Long Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets rowCount = 2 With ws Do Until IsEmpty(Cells(rowCount + 1, "D")) If (Cells(rowCount, "D") <> Cells(rowCount + 1, "D")) Then Range(Cells(rowCount + 1, "D"), Cells(rowCount + 2, "D")).EntireRow.Insert Shift:=xlDown rowCount = rowCount + 3 Else rowCount = rowCount + 1 End If Loop End With Next ws End Sub 

谢谢大家的回应。 使用ws.Cells和ws.Rows导致Do Until语句不起作用。 一旦我删除了ws。 行可以被添加。 它仍然不会遍历所有的工作表。

编辑代码以提供我目前正在使用的内容。

你正在增加行数在第一张纸,我猜你的下一张/ s没有更多的行比较第一张。 所以移动你的rowCount For Each Loop ,像这样:

 'rowCount = 2 'set to start row 'REMOVE FROM HERE For Each ws In ThisWorkbook.Worksheets rowCount = 2 'set to start row Do Until IsEmpty(Cells(rowCount + 1, "D")) 

所以在每张表格中,行将从2开始。也包含在注释中build议的所有更改。

对Scott ^ 2(Holtzman和Craner)的后续处理,您需要引用For Each循环中的所有对象。 我更喜欢使用With ws ,它清理和简化了你的代码,embedded在With语句中的所有对象都有. 作为前缀( .Cells(rowCount, "D").Rows(rowCount + 1).Insert Shift:=xlDown )。

另外,在插入2行之前不需要select行(总是最好避免使用SelectSelection ),可以直接使用.Rows(rowCount + 1).Insert Shift:=xlDown

完整的“清洁”代码

 Option Explicit Sub InsertBlankRow() Dim rowCount As Long Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets rowCount = 2 'set to start row With ws Do Until IsEmpty(.Cells(rowCount + 1, "D")) If .Cells(rowCount, "D") <> .Cells(rowCount + 1, "D") Then .Rows(rowCount + 1).Insert Shift:=xlDown .Rows(rowCount + 1).Insert Shift:=xlDown rowCount = rowCount + 3 Else rowCount = rowCount + 1 End If Loop End With Next ws End Sub 

额外 :如果要在D列中用不同的值在1行代码行之间插入2行,请使用下面的代码行:

 .Range(.Cells(rowCount + 1, "D"), .Cells(rowCount + 2, "D")).EntireRow.Insert Shift:=xlDown