遍历每个单元格

Loop through each cell

所以,基本上我正在做的是用 MS Excel 制作一款名为 Minesweeper 的游戏。现在我在尝试 运行 我的 ''new game'' 后出现错误,它说

有问题

For Each myCell In Range(strBoardSize)

我的完整代码用于查看范围内的所有单元格,如果一个单元格位于任意数量的项目旁边,它将显示其外围的项目数量。我知道可能有更简单的编码方法,但请不要评判我,因为我是初学者。

Sub WorkOutMines()

Dim myCell As Range
Dim intCountSurroundingCells

For Each myCell In Range(strBoardSize)

intCountSurroundingCells = 0

If myCell.Value = "x" Then
Else
    If myCell.Offset(-1, -1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(-1, 0).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(-1, 1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(0, -1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(0, 1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(1, -1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(1, 0).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If myCell.Offset(1, 1).Value = "x" Then
        intCountSurroundingCells = intCountSurroundingCells + 1
    End If

    If intCountSurroundingCells = 0 Then
    Else
        myCell.Value = intCountSurroundingCells
    End If

End If

Next

End Sub

已声明 strBoardSize:

Sub SetBoardSize()

strBoardSize = "Board9x9"

End Sub

您似乎需要创建变量 "strBoardSize" 并设置您想要的范围。如果 "strBoardSize" 是工作簿中的命名范围,则正确的语法为:

For Each myCell in Range("strBoardSize")

您应该在 "WorkoutMines" 子中声明该变量。

Dim strBoardSize as String 

然后你可以设置变量变量

strBoardSize = "Board9x9"

如果您不在同一个子过程中声明变量,它将不会保留它的值。