确定两个连续单元格是空白的

下面的While循环意味着迭代一列,直到find两个连续的空白单元格。 只要curCell为空,它将立即退出,忽略lastCell中的值。 在debugging的时候,我已经validation了lastCell有一个值并且不是空的,但是循环仍然存在。 我的和声明有什么问题?

While (lastCell <> "") And (curCell <> "") lastCell = curCell ActiveCell.Offset(1, 0).Select curCell = ActiveCell Wend 

你应该使用Or而不是And。

并且要求这两个语句都为true,以便while循环继续。 如果其中一个语句是假的(如果一个单元格是空的),while循环将会退出。

使用或者,while语句将继续,直到两个单元格都为空。

如果可能的话,这是一个更好的方法来做你想做的事情,因为它从第二行一直看到最后一行。 当它发现前两个单元都是空的时它会停下来。

 Sub findTwoEmptyCells() Dim lastRow As Long, i As Long Dim firstEmptyCell As Range lastRow = Cells(Rows.Count, 1).End(xlUp).Row ' Assuming your column A has the most data or is the row you want to check. For i = 1 To lastRow If Cells(i, 1).Value = "" And Cells(i, 1).Offset(1, 0).Value = "" Then Set firstEmptyCell = Cells(i, 1) Exit For End If Next i 'Now, you have a cell, firstEmptyCell, which you can do things with, ie firstEmptyCell.Value = "Empty!" End Sub 

编辑:另外,即使在一行没有两个空单元格,在firstEmptyCell.Value之前添加这个:

 If firstEmptyCell Is Nothing Then ' If there are no two empty cells in a row, exit the sub/do whatever you want MsgBox ("There are no two empty cells in a row") Exit Sub End If 

Edit2:正如@MatsMug指出,这将工作正常,假设你不改变/使用多个工作表。 如果是这样,请在Cells() ,即Sheets("Sheet1").Cells(...)之前添加表格名称。

while(lastCell <>“”)And(curCell <>“”)should be:While Not(lastCell =“”and curCell =“”)因为除了其他的改进代码的注释之外,这样的循环运行,直到最后和当前都是空的,这正是你要找的。