Visual Basic : While文による繰り返し処理

Visual Basicで繰り返し処理をするwhile文を使う例を紹介します。

概要

Visual Basicで条件を満たすまで繰り返すループ処理を実現する場合には while文を利用します。

書式

While 条件式
  ...処理
End While

プログラム例

コード

コンソールアプリケーションで以下のコードを記述します。
Module Module1

    Sub Main()
        Dim value As Integer
        value = 0

        While value < 20
            Console.Write(value & ", ")
            value += 1
        End While
        Console.ReadLine()
    End Sub

End Module

実行結果

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,

Visual Basic : While文による繰り返し処理:画像1

While True ... の場合

下記の記述をすると無限ループになります。whileループ内でExit WhileやExit Subなどでループを抜ける処理が必要になります。
 while True
   ...処理
 End While

コード例

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
  Dim a As Integer
  a = 0

  While True
    TextBox1.Text += a.ToString() + " "
    a += 1
    If (10 < a) Then Exit While
  End While
End Sub

実行結果

0 1 2 3 4 5 6 7 8 9 10

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2011-10-06
Copyright © 1995–2025 iPentec all rights reserverd.