' Generates Magic Rectangles of order 2 x 5

' Tested with Office 2007 under Windows 7

Sub MgcRect52()

Dim a(10)

y = MsgBox("Locked", vbCritical, "Routine MgcRect52")
End

n2 = 0: n3 = 0: n9 = 0: k1 = 1: k2 = 1
m1 = 0: m2 = 16: s1 = 5 * m2

'   Generate data

t1 = Timer

For j1 = 1 To 10: a(j1) = 0: Next j1

For j10 = m1 To m2                                       'a(10)
a(10) = j10

For j9 = m1 To m2                                        'a(9)
If j9 = j10 Then GoTo 90
a(9) = j9

For j8 = m1 To m2                                        'a(8)
If j8 = j9 Or j8 = j10 Then GoTo 80
a(8) = j8

For j7 = m1 To m2                                        'a(7)
If j7 = j8 Or j7 = j9 Or j7 = j10 Then GoTo 70
a(7) = j7

a(6) = s1 / 2 - a(7) - a(8) - a(9) - a(10)
If a(6) < m1 Or a(6) > m2 Then GoTo 70
a(5) = s1 / 5 - a(10)
If a(5) < m1 Or a(5) > m2 Then GoTo 70
a(4) = s1 / 5 - a(9)
If a(4) < m1 Or a(4) > m2 Then GoTo 70
a(3) = s1 / 5 - a(8)
If a(3) < m1 Or a(3) > m2 Then GoTo 70
a(2) = s1 / 5 - a(7)
If a(2) < m1 Or a(2) > m2 Then GoTo 70
a(1) = s1 / 5 - a(6)
If a(1) < m1 Or a(1) > m2 Then GoTo 70

'                           Exclude solutions with identical numbers

GoSub 800: If fl1 = 0 Then GoTo 70

n9 = n9 + 1: GoSub 640 'Print results (selected numbers)
'                           n9 = n9 + 1: GoSub 650 'Print results (squares)

70  Next j7
80  Next j8
90  Next j9
100 Next j10

t2 = Timer

t10 = Str(t2 - t1) + " sec., " + Str(n9) + " Solutions for sum" + Str(s1)
y = MsgBox(t10, 0, "Routine MgcRect52")

End

'   Print results (selected numbers)

640 For i1 = 1 To 10
Cells(n9, i1).Value = a(i1)
Next i1

Return

'   Print results (squares)

650 n2 = n2 + 1
If n2 = 5 Then
n2 = 1: k1 = k1 + 3: k2 = 1
Else
If n9 > 1 Then k2 = k2 + 6
End If

Cells(k1, k2 + 1).Select
Cells(k1, k2 + 1).Font.Color = -4165632
Cells(k1, k2 + 1).Value = n9

i3 = 0
For i1 = 1 To 2
For i2 = 1 To 5
i3 = i3 + 1
Cells(k1 + i1, k2 + i2).Value = a(i3)
Next i2
Next i1

Return

'   Exclude solutions with identical numbers

800 fl1 = 1
For j1 = 1 To 10
a2 = a(j1)
For j2 = (1 + j1) To 10
If a2 = a(j2) Then fl1 = 0: Return
Next j2
Next j1
Return

End Sub