I would like to know what is wrong with my coding as I am unable to end my do while loop in Microsoft Excel VBA. I wish to end this do while loop if the next line is blank.
Do While Cells(RowName, 1) <> ""
Name = Cells(RowName, ColumnName)
MsgBox Name
RowName = RowName + 1
Loop
Please enlighten me as I am still a beginner. The MsgBox kept popping out and does not end even if it is blank.
"Exit Do" - You can use this command wherever you want your loop to be stopped.
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's answer is very close but has a few problems. Here's how I would do it. Do while not empty and Exit Do if trimmed value is blank 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 should always be declared as Long to avoid overflow error as Excel has more than a million rows.
Also it's better and clearer if you declare and set a worksheet variable. You should always avoid unqualified range/cells references.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With