第9講 For文以外の様々なループ文

第8話 Do文の強制終了

Do While...Loop文の場合
  Private Sub CommandButton1_Click()

  Dim h As Long, o As Long, b As Long

  h = Cells(5, 2)
  o = Cells(6, 2)
  b = Cells(7, 2)
  f1 h, o, b '1乗の和の計算
  f2 h, o, b '2乗の和の計算
  f3 h, o, b '3乗の和の計算
  f4 h, o, b '4乗の和の計算

End Sub

'1乗の和の計算
Sub f1(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do While 1
    w = w + i
    i = i + b
    If w + i > o Then Exit Do
  Loop

  Cells(9, 4) = w

End Sub

'2乗の和の計算
Sub f2(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do While 1
    w = w + i * i
    i = i + b
    If w + i * i > o Then Exit Do
  Loop

  Cells(10, 4) = w

End Sub

'3乗の和の計算
Sub f3(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long

  w = 0
  i = h
  Do While 1
    w = w + i * i * i
    i = i + b
    If w + i * i * i > o Then Exit Do
Loop

    Cells(11, 4) = w

End Sub

'4乗の和の計算
Sub f4(h As Long, o As Long, b As Long)

Dim i As Long, w As Long

  w = 0
  i = h
  Do While 1
    w = w + i * i * i * i
    i = i + b
    If w + i * i * i * i > o Then Exit Do
  Loop

  Cells(12, 4) = w

End Sub

強制終了を使って、終了させることも出来ますが、次のように組んでも結果は同じです。
'1乗の和の計算
Sub f1(h As Long, o As Long, b As Long)

  Dim i As Long, w As Long, a As Byte

  w = 0
  i = h
  a = 1
  Do While a
    w = w + i
    i = i + b
    If w + i > o Then a = 0
  Loop

  Cells(9, 4) = w

End Sub

これでFor文以外の様々なループ文の学習は終わりとし、
第10講では、Subプロシージャの再帰的使用について学習します。



第7話へ 第10講第1話へ

004


vc++講義へ
vb講義へ
VB講義基礎へ
初心者のための世界で一番わかりやすいVisual C++入門基礎講座へ
初心者のための世界で一番わかりやすいVisual Basic入門基礎講座へ

数学研究室に戻る