刚学完数组和字典后尝试的,当时听群友说运用递归才好,可还没有学到递归,所以想到的方法比较简单。在这个基础上还可以加上其它的求解数独办法,至少可以求解简单级别的数独,但是中级往上的数独应该就要用假设赋值才行,这个一时还没有想到
Sub as1()
Set d = CreateObject("scripting.dictionary")
'On Error Resume Next
a = 0
b = 0
For x = 1 To 9
For y = 1 To 9
For sz = 1 To 9 '若空,则同行列进字典
If Cells(x, y) = "" Then
d(Cells(sz, y).Value) = Cells(sz, y).Value: d(Cells(x, sz).Value) = Cells(x, sz).Value: d(0) = 0
Else:
GoTo 1
End If
Next sz
For a = 0 To 6 Step 3 '同9宫格内的内容进字典
For b = 0 To 6 Step 3
If a < x And x < a + 4 And b < y And y < b + 4 Then
d(Cells(1 + a, 1 + b).Value) = Cells(1 + a, 1 + b).Value: d(Cells(1 + a, 2 + b).Value) = Cells(1 + a, 2 + b).Value: d(Cells(1 + a, 3 + b).Value) = Cells(1 + a, 3 + b).Value: d(Cells(2 + a, 1 + b).Value) = Cells(2 + a, 1 + b).Value: d(Cells(2 + a, 2 + b).Value) = Cells(2 + a, 2 + b).Value: d(Cells(2 + a, 3 + b).Value) = Cells(2 + a, 3 + b).Value: d(Cells(3 + a, 1 + b).Value) = Cells(3 + a, 1 + b).Value: d(Cells(3 + a, 2 + b).Value) = Cells(3 + a, 2 + b).Value: d(Cells(3 + a, 3 + b).Value) = Cells(3 + a, 3 + b).Value
End If
Next b
Next a
If d.Count = 9 Then '满足条件输出答案
Cells(x, y) = 45 - d(1) - d(2) - d(3) - d(4) - d(5) - d(6) - d(7) - d(8) - d(9): d.RemoveAll
Else
d.RemoveAll
End If
1
Next y
Next x
End Sub