橋平礼の電験三種合格講座

過去50年分以上の電験三種の問題を解いて分かった、電験三種は今も昔も変わりません。過去問を解きながら合格を目指しましょう。

MENU

Re5:50歳から始めるラズベリーパイ-3

Re5:50歳から始めるラズベリーパイ

簡単なゲームで学ぶVBAプログラミング入門

amazon kindleを出版しました。


3.2 魔方陣の作成-2

 

プログラムは次のようになります。
Option VBAsupport 1

Dim table(3, 3) As Integer

Sub Main

Dim x(4) As Integer '角の値を決めます。
Dim y(4) As Double
Dim n As Integer '表示個数の制限

Dim wi As Integer

'罫線、列行の幅と高さなど設定
Range("A1: E4 ").Clear 'A1からE4の範囲をクリア"
Range("A1:E4").Font.Size = 32'フォントサイズ
Range("A1:E4").HorizontalAlignment = xlCenter'センタリング

Range("A:E").ColumnWidth = 7
wi = Columns("A").Width '幅を取得する
Range("1:4").RowHeight = wi

'xlHairline:極細, xlThin:細い, xlMedium:中くらい、xlThick:太い
Range("B1:D3").Borders.Weight = xlThin '細い線,
''xlContinuous:細い実線, xlDash:破線, xlDashDot:一点鎖線, xlDashDotDot:二点鎖線
'xlDot:点線, xlDouble:二重線, xlSlantDashDot:斜破線, xlLineStyleNone:無し
Range("B1:D3").Borders.LineStyle = xlContinuous

'中央は5なので
table(1, 1) = 5

LP1: '角の和が10でなかったら戻る

'y(i)に乱数を入力
 For i = 0 To 3
   y(i) = Rnd
   x(i) = (i + 1) * 2
 Next i

'y(i)の値でソートしています。
 For i = 0 To 2
   For ii = i + 1 To 3
     If (y(i) < y(ii)) Then
       t1 = y(ii)
       y(ii) = y(i)
       y(i) = t1
       t2 = x(ii)
      x(ii) = x(i)
      x(i) = t2
    End If
  Next ii
 Next i


'もし対角線の和が10でなかったらもどる。
If (x(0) + x(3)) <> 10 Then
     GoTo LP1
End If

table(0, 0) = x(0) '角は偶数
table(0, 2) = x(1)
table(2, 0) = x(2)
table(2, 2) = x(3)

table(0, 1) = 15 - table(0, 0) - table(0, 2)
table(2, 1) = 15 - table(2, 0) - table(2, 2)
table(1, 0) = 15 - table(2, 0) - table(0, 0)
table(1, 2) = 15 - table(2, 2) - table(0, 2)

n = 1
 For i = 0 To 2
   For ii = 0 To 2
     If (Rnd > 0.4 And n < 5) Then
       Cells(i + 1, ii + 2) = table(i, ii)
       n = n + 1
     End If 
   Next ii
 Next i

'正解を表示
 For i = 0 To 2
   For ii = 0 To 2
     Cells(i + 1, ii + 10) = table(i, ii)
   Next ii
 Next i

End Sub

'ボタンをクリックしたら
Sub Button1_Click()

Dim n1 As Integer '値計算
Dim n2 As Integer '値計算
Dim n3 As Integer '値計算

n1 = 0
n2 = 0
n3 = 0
'横方向に合計計算
 For i = 0 To 2
   n1 = n1 + Cells(1, i + 2)
   n2 = n2 + Cells(2, i + 2)
   n3 = n3 + Cells(3, i + 2)
 Next

Cells(1, 5).Value = n1
Cells(2, 5).Value = n2
Cells(3, 5).Value = n3

n1 = 0
n2 = 0
n3 = 0
'縦方向に合計計算
 For i = 0 To 2
   n1 = n1 + Cells(i + 1, 2)
   n2 = n2 + Cells(i + 1, 3)
   n3 = n3 + Cells(i + 1, 4)
 Next

Cells(4, 2).Value = n1
Cells(4, 3).Value = n2
Cells(4, 4).Value = n3
'斜め方向に合計計算
Cells(4, 5).Value = Cells(1, 2).Value + Cells(2, 3).Value + Cells(3, 4).Value
Cells(4, 1).Value = Cells(3, 2).Value + Cells(2, 3).Value + Cells(1, 4).Value

'全部15になっている?
 If (Cells(1, 5).Value = 15 And Cells(2, 5).Value = 15 And Cells(3, 5).Value = 15) Then
  If (Cells(4, 2).Value = 15 And Cells(4, 3).Value = 15 And Cells(4, 4).Value = 15) Then
   If (Cells(4, 1).Value = 15 And Cells(4, 5).Value = 15) Then
     MsgBox ("正解!!")
   End If
 End If
End If

End Sub