Friday, 4 April 2014

Creating a game board in Excel
























The following code creates the board starting at (xo, yo) and with squares of size side. Each square is named based on the coordinates (you can choose your own method for this but I've just used 0-63. Equally you could name them by their chess coords A1-H8). The colour of the square is chosen to alternate like a chess board. You can change the border colour also as required. Finally, the "action" (what happens when it is clicked) is set to call the macro "click" which in this example simply displays a message box with the square name.


Sub CreateBoard()
Const side = 50
Const xo = 200
Const yo = 50

Dim x As Integer, y As Integer

    For y = 0 To 7
        For x = 0 To 7
            ActiveSheet.Shapes.AddShape(msoShapeRectangle, _
                xo + x * side, yo + y * side, side, side).Select
            Selection.Name = "square" & x + y * 8
            Selection.OnAction = "click"
            
            If (x + y) Mod 2 = 1 Then
                Selection.ShapeRange.Fill.ForeColor.RGB = _
                     RGB(0, 0, 0)
                Selection.ShapeRange.Line.ForeColor.RGB = _
                     RGB(0, 0, 0)
            Else
                Selection.ShapeRange.Fill.ForeColor.RGB = _
                    RGB(200, 200, 200)
                Selection.ShapeRange.Line.ForeColor.RGB = _
                    RGB(200, 200, 200)
            End If
        Next
    Next
End Sub

Sub click()
    MsgBox Application.Caller

End Sub



Download Excel file here: 20140404 - BoardGameEx.xlsm

No comments:

Post a Comment