如何在VBA中结束一个while while循环

我想知道我的代码有什么问题,因为我无法在Microsoft Excel VBA中结束我的while循环。 如果下一行是空白,我希望结束这个while while循环。

Do While Cells(RowName, 1) <> "" Name = Cells(RowName, ColumnName) MsgBox Name RowName = RowName + 1 Loop 

请赐教,因为我还是个初学者。 MsgBox保持popup状态,即使空白也不会结束。

“退出” – 您可以在需要停止循环的地方使用此命令。

 Sub ExitDoSample Dim rowname As Integer Dim ColumnName As Integer rowname = 1 ColumnName = 1 Do While Cells(RowName, 1) <> "" Name = Cells(rowname, ColumnName).Value If Name = "" Or IsEmpty(Name) Then Exit Do Else MsgBox Name End If rowname = rowname + 1 Loop End Sub 

Sankar Balasubramanian的答案非常接近,但有一些问题。 这是我将如何做到这一点。 如果修剪值为空string,则不要清空并退出。

 Sub SampleEnding() Dim ws As Worksheet: Set ws = ActiveSheet Dim RowNum As Long: RowNum = 1 Dim ColNum As Long: ColNum = 3 Dim Name As String Do While Not IsEmpty(ws.Cells(RowNum, 1)) If Trim(ws.Cells(RowNum, 1).Value) <> "" Then Name = ws.Cells(RowNum, ColNum) MsgBox Name Else Exit Do End If RowNum = RowNum + 1 Loop End Sub 

RowNum应该总是声明为Long,以避免溢出错误,因为Excel有超过一百万行。

另外,如果声明并设置工作表variables,则会更好,更清晰。 你应该总是避免不合格的范围/单元格引用。

您正在检查列1中的行RowName是否为空,但是您是从列ColumnName(可能不是列1)中选取名称。因此,列1中可能有数据(所以检查通过并且循环继续)但列号。 ColumnName可能是空的,所以你的消息框显示一些空白。 这可能是问题吗?