Sub ProduireCarréMagique()
Dim Coté As Long, RngCM As Range, T
On Error Resume Next
Set RngCM = [LeCarréMagique]: If Err Then MsgBox "Plage nommée ""LeCarréMagique"" introuvable.", vbCritical, "ProduireCarréMagique": Exit Sub
Coté = ActiveSheet.[Coté].Value: If Err Then MsgBox "Plage nommée ""Coté"" introuvable.", vbCritical, "ProduireCarréMagique": Exit Sub
RngCM.ClearContents
Set RngCM = RngCM.Resize(Coté, Coté)
RngCM.Value = CarréMagique(Coté)
RngCM.Worksheet.Names.Add "LeCarréMagique", RngCM
End Sub
Function CarréMagique(ByVal Coté As Long) As Variant()
CalculCarréMagique CarréMagique, Coté
End Function
Sub CalculCarréMagique(T(), ByVal Coté As Long)
Dim M As Long, Y As Long, X As Long, L As Long, C As Long, N As Long
ReDim T(1 To Coté, 1 To Coté)
M = Coté \ 2
For Y = -M To M: For X = -M To M
N = N + 1
L = X + Y + M + Coté
C = X - Y + M + Coté
T(L Mod Coté + 1, C Mod Coté + 1) = N
Next X, Y
End Sub