第4講 同じこと(同様なこと)の繰り返し
第10話 成績一覧表の完成


(データは毎回異なったものになります。)
前話問題解答例
Private Sub CommandButton1_Click()
  Cells(6, 2) = "出席番号"
  Cells(6, 3) = "国語"
  Cells(6, 4) = "社会"
  Cells(6, 5) = "数学"
  Cells(6, 6) = "理科"
  Cells(6, 7) = "英語"
  Cells(6, 8) = "合計"
  Dim i As Byte
  For i = 1 To 10
    Cells(6 + i, 2) = i
    Cells(6 + i, 3) = Int(100 * Rnd())
    Cells(6 + i, 4) = Int(100 * Rnd())
    Cells(6 + i, 5) = Int(100 * Rnd())
    Cells(6 + i, 6) = Int(100 * Rnd())
    Cells(6 + i, 7) = Int(100 * Rnd())
  Next
  Cells(17, 2) = "合計"
End Sub

さて、次の課題です。
For文を使い各教科の合計および各生徒の合計を計算させましょう。

解答例は30行下。
































解答例
Private Sub CommandButton1_Click()
  Cells(6, 2) = "出席番号"
  Cells(6, 3) = "国語"
  Cells(6, 4) = "社会"
  Cells(6, 5) = "数学"
  Cells(6, 6) = "理科"
  Cells(6, 7) = "英語"
  Cells(6, 8) = "合計"
  Dim i As Byte, w As Integer
  For i = 1 To 10
    Cells(6 + i, 2) = i
    Cells(6 + i, 3) = Int(100 * Rnd())
    Cells(6 + i, 4) = Int(100 * Rnd())
    Cells(6 + i, 5) = Int(100 * Rnd())
    Cells(6 + i, 6) = Int(100 * Rnd())
    Cells(6 + i, 7) = Int(100 * Rnd())
  Next
  w = 0
  For i = 1 To 10
    w = w + Cells(6 + i, 3)
  Next
  Cells(17, 3) = w
  w = 0
  For i = 1 To 10
    w = w + Cells(6 + i, 4)
  Next
  Cells(17, 4) = w
  w = 0
  For i = 1 To 10
    w = w + Cells(6 + i, 5)
  Next
  Cells(17, 5) = w
  w = 0
  For i = 1 To 10
    w = w + Cells(6 + i, 6)
  Next
  Cells(17, 6) = w
  w = 0
  For i = 1 To 10
    w = w + Cells(6 + i, 7)
  Next
  Cells(17, 7) = w
  w = 0
  For i = 1 To 5
    w = w + Cells(7, 2 + i)
  Next
  Cells(7, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(8, 2 + i)
  Next
  Cells(8, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(9, 2 + i)
  Next
  Cells(9, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(10, 2 + i)
  Next
  Cells(10, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(11, 2 + i)
  Next
  Cells(11, 8) = w
  w = 0
  For i = 1 To 5
    w = w + Cells(12, 2 + i)
  Next
  Cells(12, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(13, 2 + i)
  Next
  Cells(13, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(14, 2 + i)
  Next
  Cells(14, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(15, 2 + i)
  Next
  Cells(15, 8) = w
  w = 0
   For i = 1 To 5
    w = w + Cells(16, 2 + i)
  Next
  Cells(16, 8) = w
  Cells(17, 2) = "合計"
End Sub

実は、このプログラミング褒められたものではありません。
理由は、同じことの繰り返しを人間がやっているからです。
繰り返しは、やはりコンピュータにさせるべきです。
ただ、この課題を実現するには、
同じことの縦横の繰り返し(専門用語では2次元ループ)を学習しなければなりません。
同じことの縦横の繰り返しは、第9講で学ぶ予定になっています。


第9話へ 第5講第1話へ

トップ

vc++講義へ

初心者のための世界で一番わかりやすいVisual C++入門基礎講座
初心者のための世界で一番わかりやすいVisual Basic入門基礎講座へ
vb講義へ
VB講義基礎へ
初心者のためのJava 入門 基礎から応用まで
数学研究室に戻る