2x'love'和1x'Do Until' - >无法运行宏

时间:2014-05-19 11:44:52

标签: excel vba excel-vba

我正在尝试创建一个简单的算法来生成数独游戏桌。我遇到了以下问题。我的代码的主要部分是Do until循环。但是当有两个“循环”短语时我无法运行宏。谁能告诉我为什么会这样?有没有办法克服这个问题?我会非常感谢任何提示。如果您的帖子含糊不清或与您的期望不符,我也非常感谢(因为我是论坛的新手)。 代码如下:(有问题的时刻标有评论)
    副MAIN()

Dim a, r, c, V As Integer

r = 2
c = 2
Do Until r = 11 And c = 2
a = Sheets("LIST").Columns("B").Cells.Find("*", SearchOrder:=xlByRows,  LookIn:=xlValues, SearchDirection:=xlPrevious).Row - 1

V = Int(a * Rnd + 1)
Sheets("GAME").Cells(r, c).Value = V
If V = 5 Then 'This condition is a test-condition. In the final version of code there should be more sophisticated condition.
Sheets("LIST").Range("B" & V - 1).Delete Shift:=xlUp
Loop '(this is the first loop)
End If

If c = 10 Then
r = r + 1
c = 2
Else
c = c + 1
End If
Sheets("LIST").Cells(2, 2).Value = 1
Sheets("LIST").Cells(2, 3).Value = 2
Sheets("LIST").Cells(2, 4).Value = 3
Sheets("LIST").Cells(2, 5).Value = 4
Sheets("LIST").Cells(2, 6).Value = 5
Sheets("LIST").Cells(2, 7).Value = 6
Sheets("LIST").Cells(2, 8).Value = 7
Sheets("LIST").Cells(2, 9).Value = 8
Sheets("LIST").Cells(2, 10).Value = 9
Loop '(this is the second loop)
End Sub

2 个答案:

答案 0 :(得分:1)

一个快速注释(供参考),您可以使用With... End With构造保存相当多的输入:

'...
With Sheets("LIST")
    .Cells(2, 2) = 1
    .Cells(3, 2) = 2
    .Cells(4, 2) = 3
    '...
End With

然后,如果你感觉很狂野,你可以用For...Next循环填充你的sodoku广场:

'...
Dim SizeOfSquare As Long, Index As Long
SizeOfSquare = 9

With Sheets("LIST")
    For Index = 1 To SizeOfSquare
        .Cells(Index + 1, 2) = Index
    Next Index
End With

懒惰并不总是坏事!

答案 1 :(得分:0)

好的,在我发布它之后,我想出了一个解决方案! 对不起,我已经在论坛上发布了。这是修改后的代码:
(我会留在这里以防有人像我一样有这么愚蠢的问题:))

Sub MAIN()

Dim a, r, c, V As Integer

r = 2
c = 2
Do Until r = 11 And c = 2
a = Sheets("LIST").Columns("B").Cells.Find("*", SearchOrder:=xlByRows,     LookIn:=xlValues, SearchDirection:=xlPrevious).Row - 1

V = Int(a * Rnd + 1)
Sheets("GAME").Cells(r, c).Value = V
If V = 5 Then
Sheets("LIST").Range("B" & V - 1).Delete Shift:=xlUp

Else

If c = 10 Then
r = r + 1
c = 2
Else
c = c + 1
End If
Sheets("LIST").Cells(2, 2).Value = 1
Sheets("LIST").Cells(3, 2).Value = 2
Sheets("LIST").Cells(4, 2).Value = 3
Sheets("LIST").Cells(5, 2).Value = 4
Sheets("LIST").Cells(6, 2).Value = 5
Sheets("LIST").Cells(7, 2).Value = 6
Sheets("LIST").Cells(8, 2).Value = 7
Sheets("LIST").Cells(9, 2).Value = 8
Sheets("LIST").Cells(10, 2).Value = 9
End If
Loop
End Sub