簡體   English   中英

遍歷每個單元格

[英]Loop through each cell

因此,基本上我正在做的是使用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

看起來您需要創建變量“ strBoardSize”並設置所需的范圍。 如果“ strBoardSize”是工作簿中的命名范圍,則正確的語法為:

For Each myCell in Range("strBoardSize")

您應該在“ WorkoutMines”子句中聲明該變量。

Dim strBoardSize as String 

然后您可以將變量設置為

strBoardSize = "Board9x9"

如果未在同一子過程中聲明變量,則該變量將無法保持其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM