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

第2話 While文によるいろいろな和の計算

Private Sub CommandButton1_Click()

  Dim w As Integer, i As Integer, n As Integer

  w = 0
  i = 1
  n = Cells(5, 2)

  Do Until i > 10
    w = w + i
    i = i + 1
  Loop
  Cells(6, 2) = n
  Cells(6, 4) = w

End Sub

ではシートを改良して、いろいろな計算が出来るようにしましょう。
シート例
実行例
実行例
ただし、処理が増えてきましたので、和はそれぞれプロシージャで処理することにしましょう。
解答例は、30行下。




















コード例
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
  While i <= o
    w = w + i
    i = i + b
  Wend

  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
  While i <= o
    w = w + i * i
    i = i + b
  Wend

  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
  While i <= o
    w = w + i * i * i
    i = i + b
  Wend

  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
  While i <= o
    w = w + i * i * i * i
    i = i + b
  Wend

  Cells(12, 4) = w

End Sub


Private Sub CommandButton2_Click()

  Range("B5:B7,D9:D13").Select
  Selection.ClearContents
  Cells(1, 1).Select

End Sub

では同じ課題をDo While...Loop文、Do...Loop While文で実現してみましょう。




第1話へ
 第3話へ

004


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

数学研究室に戻る