Search code examples
excelvbaminesweeper

VBA Minesweeper: Check border cells for mine count?


I have not found much of an answer in VBA on this, but I am making a Minesweeper 5x5 board, and am trying to have cells surrounding a mine to display how many mines are touching it. I am able to get the middle 9 to work, ie the spaces with an "X":

-----
-XXX-
-XXX-
-XXX-
-----

But I'm having serious trouble getting the bordering cells to also count. Here is my code:

For i = 2 To 4
    For j = 2 To 4
        If BombArray(i, j) <> "X" Then
            BombArray(i, j) = 0
                If BombArray(i + 1, j - 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i + 1, j) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i + 1, j + 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i, j - 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i, j + 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i - 1, j - 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i - 1, j) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
                If BombArray(i - 1, j + 1) = "X" Then
                    BombArray(i, j) = BombArray(i, j) + 1
                End If
        End If
    Next j
Next i

I have my index set to 2 to 4 because otherwise Excel throws me an Error '9': Subscript out of range.

Any help would be greatly appreciated.


Solution

  • Test to see if you're on the boundary before you test the cell:

    For i = 1 To 5
        For j = 1 To 5
            If BombArray(i, j) <> "X" Then
                BombArray(i, j) = 0
                    If j <> 1 And i <> 5 Then
                        If BombArray(i + 1, j - 1) = "X" Then BombArray(i, j) = BombArray(i, j) + 1
                    End If
                    If i <> 5 Then
                        If BombArray(i + 1, j) = "X" Then BombArray(i, j) = BombArray(i, j) + 1
                    End If
                    'Etc.
                    '...
            End If
        Next j
    Next i