循环遍历每个单元格

时间:2015-01-19 20:41:33

标签: excel loops

所以,基本上我正在做的是用MS Excel制作一款名为Minesweeper的游戏。现在我在尝试运行“新游戏”后出现错误,并说它出现了问题

  

对于每个myCell范围内(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

2 个答案:

答案 0 :(得分:0)

看起来你需要创建变量“strBoardSize”并设置你想要的范围。如果“strBoardSize”是工作簿中的命名范围,则正确的语法为:

For Each myCell in Range("strBoardSize")

答案 1 :(得分:0)

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

Dim strBoardSize as String 

然后您可以将变量设置为变量

strBoardSize = "Board9x9"

如果你没有在同一个子程序中声明变量,它就不会保留它的值。