Excel 2021 调试通过
程序代码:
Option Explicit
Sub aa()
Dim b(6)
Dim i, j, m, n, t
Randomize
'读和值及求和
m = 0
n = 0
b(0) = Cells(1, 1)
For i = 2 To 4
b(i - 1) = Cells(1, i)
m = m + b(i - 1)
b(i + 2) = Cells(i, 1)
n = n + b(i + 2)
Next i
'校验
If m <> b(0) Or n <> b(0) Then
MsgBox "和值校验失败", vbCritical, "错误"
Exit Sub
End If
'循环,最后一次不用管
For t = 1 To 5
'查询最小值
m = 0
For i = 1 To 6
If b(m) > b(i) Then
m = i
End If
Next i
'开始填值
If m <= 3 Then '区分一下。算法是一样的,但引用的单元格方向有差异,不愿写子函数了
'填第一个格子
If Cells(2, m + 1) = "" Then
If Cells(3, m + 1) = "" Then
If Cells(4, m + 1) = "" Then
Cells(2, m + 1) = Int(Rnd() * (Cells(1, m + 1) - 3) + 1)
Else
Cells(2, m + 1) = Int(Rnd() * (Cells(1, m + 1) - Cells(4, m + 1) - 2) + 1)
End If
Else
If Cells(4, m + 1) = "" Then
Cells(2, m + 1) = Int(Rnd() * (Cells(1, m + 1) - Cells(3, m + 1) - 2) + 1)
Else
Cells(2, m + 1) = Cells(1, m + 1) - Cells(3, m + 1) - Cells(4, m + 1)
End If
End If
End If
'填第二个格子
If Cells(3, m + 1) = "" Then
If Cells(4#, m + 1) = "" Then
Cells(3, m + 1) = Int(Rnd() * (Cells(1, m + 1) - Cells(2, m + 1) - 1) + 1)
Else
Cells(3, m + 1) = Cells(1, m + 1) - Cells(2, m + 1) - Cells(4, m + 1)
End If
End If
'填第三个格子
If Cells(4, m + 1) = "" Then
Cells(4, m + 1) = Cells(1, m + 1) - Cells(2, m + 1) - Cells(3, m + 1)
End If
Else
'填第一个格子
If Cells(m - 2, 2) = "" Then
If Cells(m - 2, 3) = "" Then
If Cells(m - 2, 4) = "" Then
Cells(m - 2, 2) = Int(Rnd() * (Cells(m - 2, 1) - 3) + 1)
Else
Cells(m - 2, 2) = Int(Rnd() * (Cells(m - 2, 1) - Cells(m - 2, 4) - 2) + 1)
End If
Else
If Cells(m - 2, 4) = "" Then
Cells(m - 2, 2) = Int(Rnd() * (Cells(m - 2, 1) - Cells(m - 2, 3) - 2) + 1)
Else
Cells(m - 2, 2) = Cells(m - 2, 1) - Cells(m - 2, 3) - Cells(m - 2, 4)
End If
End If
End If
'填第二个格子
If Cells(m - 2, 3) = "" Then
If Cells(m - 2, 4) = "" Then
Cells(m - 2, 3) = Int(Rnd() * (Cells(m - 2, 1) - Cells(m - 2, 2) - 1) + 1)
Else
Cells(m - 2, 3) = Cells(m - 2, 1) - Cells(m - 2, 2) - Cells(m - 2, 4)
End If
End If
'填第三个格子
If Cells(m - 2, 4) = "" Then
Cells(m - 2, 4) = Cells(m - 2, 1) - Cells(m - 2, 2) - Cells(m - 2, 3)
End If
End If
b(m) = b(0) '不让下次查找到
Next t
MsgBox "填充完成", vbInformation, "完成"
End Sub
[此贴子已经被作者于2023-6-20 16:45编辑过]