Finance

Charts

Statistics

Macros

Search

Snake Game Board Setup in Excel VBA

In the class module ThisWorkbook, you will find the procedure Workbook_Open(). This procedure sets up the game board immediately after opening the file.

 

Private Sub Workbook_Open()
    ThisWorkbook.Worksheets("Sheet1").Activate
    Cells.Delete
    Cells.RowHeight = 20
    Cells.ColumnWidth = 3.5
    ' Borders for the game board
    Range("B2:K2").Borders(xlEdgeTop).Weight = xlThick
    Range("B11:K11").Borders(xlEdgeBottom).Weight = xlThick
    Range("B2:B11").Borders(xlEdgeLeft).Weight = xlThick
    Range("K2:K11").Borders(xlEdgeRight).Weight = xlThick
    ' Start button cell
    Range("M2").Value = "Start"
    With Range("M2:O2")
        .Interior.Color = RGB(192, 192, 192)
        .MergeCells = True
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
    ' Direction control cells with neutral cell in the center
    Range("N4, M5, O5, N6").Interior.Color = RGB(192, 192, 192)
    Range("N5").Activate
    ' Counter cell
    Range("N8").Value = 0
    With Range("N8")
        .Interior.Color = vbYellow
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
    ' Info button cell
    Range("M11").Value = "Info"
    With Range("M11:O11")
        .Interior.Color = RGB(192, 192, 192)
        .MergeCells = True
        .HorizontalAlignment = xlCenter
        .VerticalAlignment = xlCenter
    End With
End Sub

Explanation:

  • The worksheet Sheet1 is activated.
  • Using the Delete method on all Cells, the sheet is cleared.
  • The row height and column width of all cells are set to create square-shaped cells (row height = 20, column width = 3.5).
  • The game board is defined by the range B2:K11, and thick borders are applied around its edges. This border defines the game boundary the snake must not collide with.
  • The cells for the START button (range M2:O2) are merged into one large cell, filled with a gray background color, and text is centered horizontally and vertically.
  • Similarly, the INFO button cells (M11:O11) are merged and formatted the same way.
  • The four cells used to control the snake’s movement direction (N4, M5, O5, N6) are shaded gray.
  • The cell N5 in the center of these direction controls is activated. This activation happens after every click to ensure the SelectionChange event fires on the next click; otherwise, clicking the same cell twice would not trigger the event.
  • The counter cell (N8) is initialized to zero and colored yellow, with centered text both horizontally and vertically.

 

0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx