|
设计一个excel表格VBA程序,单元格输入四个数字,通过四个数字的加减乘除计算后结果为24,并显示计算过程
我在网上找的代码,好像出错,师傅可以不用我的代码,重写,谢谢:
Sub FindWayTo24()
Dim nums(1 To 4) As Double
Dim i As Integer, j As Integer, k As Integer, l As Integer
Dim a As Double, b As Double, c As Double, d As Double
Dim result As Double
Dim found As Boolean
' 从单元格A1到A4获取四个数字
For i = 1 To 4
nums(i) = Cells(i, 1).Value
Next i
' 尝试所有可能的组合
found = False
For i = 1 To 4
a = nums(i)
For j = 1 To 4
If j <> i Then
b = nums(j)
For k = 1 To 4
If k <> i And k <> j Then
c = nums(k)
For l = 1 To 4
If l <> i And l <> j And l <> k Then
d = nums(l)
' 尝试所有运算组合
result = TryOperations(a, b, c, d)
If result = 24 Then
found = True
' 显示计算过程和结果
Cells(6, 1).Value = "(" & a & " " & OperationString & " " & b & ") " & OperationString2 & " " & c & " " & OperationString3 & " " & d & " = 24"
Exit For
End If
End If
Next l
If found Then Exit For
End If
Next k
If found Then Exit For
End If
Next j
If found Then Exit For
Next i
If Not found Then
Cells(6, 1).Value = "没有找到解决方案"
End If
End Sub
Function TryOperations(a As Double, b As Double, c As Double, d As Double) As Double
Dim operations As Variant
operations = Array("+", "-", "*", "/")
Dim i As Integer, j As Integer, k As Integer
Dim result As Double
For i = 0 To 3
For j = 0 To 3
For k = 0 To 3
' 尝试所有运算顺序
result = Calculate(Calculate(Calculate(a, b, operations(i)), c, operations(j)), d, operations(k))
If result = 24 Then
OperationString = operations(i)
OperationString2 = operations(j)
OperationString3 = operations(k)
TryOperations = result
Exit Function
End If
Next k
Next j
Next i
TryOperations = 0
End Function
Function Calculate(a As Double, b As Double, op As String) As Double
Select Case op
Case "+"
Calculate = a + b
Case "-"
Calculate = a - b
Case "*"
Calculate = a * b
Case "/"
If b <> 0 Then Calculate = a / b
End Select
End Function
|
|