I could not find any information on this problem in the Visual Basic language, but I am trying to generate 10 and only 10 random mines for a 5x5 Minesweeper game. My problem involves the number of mines. I often only generate 4 mines, or 10+ mines, and its always inconsistent. Here is my code:
Sub Minesweeper()
Dim i As Single
Dim Col As Single
Dim Row As Single
Dim BombArray(1 To 5, 1 To 5) As String
'assignment of mines
Do
Row = Application.WorksheetFunction.RandBetween(1, 5)
Col = Application.WorksheetFunction.RandBetween(1, 5)
1
If BombArray(Row, Col) <> "X" Then
BombArray(Row, Col) = "X"
Sheet1.Cells(4 + Row, 3 + Col).Value = BombArray(Row, Col)
Else
i = i + 1
GoTo 1
End If
Loop Until i = 10
End Sub
Any help would be greatly appreciated.
Use a standard for loop
Also since you are using an array assign the array only once after the loop:
Sub Minesweeper()
Dim i As Single
Dim Col As Single
Dim Row As Single
Dim BombArray(1 To 5, 1 To 5) As String
'assignment of mines
For i = 1 To 10
Row = Application.WorksheetFunction.RandBetween(1, 5)
Col = Application.WorksheetFunction.RandBetween(1, 5)
If BombArray(Row, Col) <> "X" Then
BombArray(Row, Col) = "X"
Else
i = i - 1
End If
Next i
Sheet1.Range("D5").Resize(UBound(BombArray, 1), UBound(BombArray, 2)).Value = BombArray
End Sub