Option Explicit
Sub ProduireCarréMagique()
Dim Coté As Long, RngCM As Range
On Error Resume Next
Coté = InputBox("Combien de nombres par coté ?")
If Err Then Exit Sub
Set RngCM = ActiveSheet.[LeCarréMagique]
If Err Then Set RngCM = Selection
On Error GoTo 0
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