Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to end a do while loop in VBA

Tags:

loops

excel

vba

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.

like image 856
Linify Avatar asked Apr 29 '16 03:04

Linify


2 Answers

"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
like image 56
Sankar Balasubramanian Avatar answered Nov 11 '22 22:11

Sankar Balasubramanian


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.

like image 32
D_Bester Avatar answered Nov 11 '22 21:11

D_Bester