ループを終了し次のループに移る (Continue文の利用) - VB

Visual Basicでループを終了し次のループに移るコードを紹介します。

概要

Visual Basicでループの途中でループを終了し次のループに移る場合はContinue文を使います。
  • Forループの場合は Continue For
  • Whileループの場合は Continue While
  • Doループの場合は Contiue Do
になります。

書式

Forループの場合
For 初期値 To 閾値 Step 増分
  ...(処理)
  Continue For
  ...(処理)
Next
Whileループの場合
While 条件式
  ...(処理)
  Continue While
  ...(処理)
End While
Doループの場合
Do While 条件式
  ...(処理)
  Continue Do
  ...(処理)
Loop

コード例

Private Sub Button7_Click(sender As System.Object, e As System.EventArgs) Handles Button7.Click
  Dim i As Integer

  For i = 0 To 10 Step 1
    If i Mod 2 = 0 Then
      Continue For
    End If
    TextBox1.Text += Convert.ToString(i) + " "
  Next
End Sub

実行結果

1 3 5 7 9
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
掲載日: 2011-10-10
iPentec all rights reserverd.