# VBA Do Loop

Just like the For Next statement, the Do Loop statement is a code repetition instruction.

Usually the Do Loop statement is used when it is known that the loop has an end, but it is not known exactly when it will occur or what it is.

There are two types of Do loop in VBA: Do While and Do Until.

## Do While

In the structure of this loop type, While is the instruction that specifies its end condition (without While the code would run indefinitely).

    X = 0
Do While X < 3

X = X + 1
Msgbox X

Loop


Note that it is similar to the If Then Else condition, if the evaluation of X < 3 is True. If so, the loop continues.

The While condition can be inserted both at the beginning (as shown above) or at the end (as shown below).

    X = 0
Do

X = X + 1
Msgbox X

Loop While X < 3


Note that in this second case you are guaranteed to run the code at least once. This occurs because the While output condition is at the end, so the input in the loop is unrestricted.

## Do Until

The Until statement is used similarly to While, but its condition for execution is False, while for While is True.

Do While Version

    X = 0
Do While X < 3

X = X + 1
Msgbox X

Loop


Do Until Version

    X = 0
Do Until X >= 3

X = X + 1
Msgbox X

Loop


Notice how the same results are obtained both using conditional: Do Loop as Do While.

## Leaving the Loop Ahead of Time

Sometimes we need VBA to exit the loop ahead of time. Usually this is done by using the conditional If...Then followed by the instruction Exit Do.

    X = 0
Do Until X > 3

If X = 0 Then
Exit Do
End If

X = X + 1
Msgbox X 'This Msgbox will not appear
Loop


The same concept is used for loops For Next, with the Exit For statement.
{"ft_lang_label":"__label__en","ft_lang_prob":0.9190594,"math_prob":0.834789,"size":1964,"snap":"2021-31-2021-39","text_gpt3_token_len":498,"char_repetition_ratio":0.13010204,"word_repetition_ratio":0.11369509,"special_character_ratio":0.24490835,"punctuation_ratio":0.09135803,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9953446,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-07-27T22:27:06Z\",\"WARC-Record-ID\":\"<urn:uuid:031a0944-ae30-4e27-ba46-7489b8fa661e>\",\"Content-Length\":\"21559\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:31c6d262-271d-4f2a-9e2e-504887cf5005>\",\"WARC-Concurrent-To\":\"<urn:uuid:4ca73be4-6976-43bc-b97e-fed2a09c67db>\",\"WARC-IP-Address\":\"134.122.22.234\",\"WARC-Target-URI\":\"https://www.superexcelvba.com/en/tutorial/013-do-loop\",\"WARC-Payload-Digest\":\"sha1:HY7X5WLHRMIUHUVA6IIWUMKDMYZPX2SQ\",\"WARC-Block-Digest\":\"sha1:ZCENJHDAKHBKYABVHYPJRXWIWJFFOKTM\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-31/CC-MAIN-2021-31_segments_1627046153491.18_warc_CC-MAIN-20210727202227-20210727232227-00454.warc.gz\"}"}