在VBA中解决数独。如何提高代码效率?

时间:2016-05-02 00:43:53

标签: vba sudoku

我一直在尝试编写将解决Sudoku的VBA代码,并发现我的代码非常臃肿。这是我到目前为止(它现在只解决了最左边的列。为了以这种方式编写其余的代码,我需要添加9 x 27个查找变量......)

Dim i, j As Integer
Dim emptyrow, emptycol As Collection
Dim emptycellcount As Integer
Dim range1, lookup1, lookup2, lookup3, lookup4, lookup5, lookup6, lookup7,    lookup8, lookup9 As Range

Set emptyrow = New Collection
Set emptycol = New Collection

''''obtain coordinates of missing cells'''

With Range("A1")
    For i = 1 To 9
        For j = 1 To 9
            If .Offset(i, j).Value = "" Then
                emptyrow.Add i
                emptycol.Add j
            End If
        Next j
    Next i
End With

emptycellcount = emptyrow.Count

Set range1 = Range("A1").Offset(1, 1).Resize(9, 1)
Set lookup1 = range1.Find(1, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup2 = range1.Find(2, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup3 = range1.Find(3, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup4 = range1.Find(4, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup5 = range1.Find(5, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup6 = range1.Find(6, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup7 = range1.Find(7, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup8 = range1.Find(8, LookIn:=xlValues, LookAt:=xlWhole)
Set lookup9 = range1.Find(9, LookIn:=xlValues, LookAt:=xlWhole)

''''populate missing cells until one of each numbers from 1 to 9 is found''''

With Range("A1")
    Do Until Not lookup1 Is Nothing And Not lookup2 Is Nothing And Not lookup3 Is Nothing And Not lookup4 Is Nothing And Not lookup5 Is Nothing And Not lookup6 Is Nothing And Not lookup7 Is Nothing And Not lookup8 Is Nothing And Not lookup9 Is Nothing
    For i = 1 To emptycellcount
        .Offset(emptyrow(i), emptycol(i)).Value = Int((9 - 1 + 1) * Rnd + 1)
    Next i

    Set lookup1 = range1.Find(1, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup2 = range1.Find(2, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup3 = range1.Find(3, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup4 = range1.Find(4, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup5 = range1.Find(5, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup6 = range1.Find(6, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup7 = range1.Find(7, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup8 = range1.Find(8, LookIn:=xlValues, LookAt:=xlWhole)
    Set lookup9 = range1.Find(9, LookIn:=xlValues, LookAt:=xlWhole)

    Loop
End With

End Sub

所以我想我的问题是:

  1. 我是否在正确的轨道上?使用我的逻辑线是否有更有效的方法?
  2. 是否有完全不同的,更好的方法来编写代码?
  3. 谢谢!

0 个答案:

没有答案