excel - 不断收到运行时错误“5”VBA,这是什么问题?
问题描述
我正在创建可以求解二次方程的代码,但是我不断收到此错误。它每次都突出显示 x= 函数。我不知道它有什么问题,请帮助。代码如下。
Option Explicit
Sub main()
Dim a As Double
Dim b As Double
Dim c As Double
Dim x1 As Long
a = InputBox("Write a number for a")
b = InputBox("Write a number for b")
c = InputBox("Write a number for c")
x1 = (-b + Sqr((b ^ 2) - (4 * a * c))) / (2 * a)
MsgBox (x1)
End Sub
编辑:感谢我能够运行该程序的帮助。但是,当我尝试将 x1 和 x2 转换回等式时,我得到的数字似乎没有意义。
Option Explicit
Sub main()
Dim a As Double
Dim b As Double
Dim c As Double
Dim x1 As Double
Dim x2 As Double
a = InputBox("Write a number for a")
b = InputBox("Write a number for b")
c = InputBox("Write a number for c")
'If statement to check if items inside sqr are negative. Being negative would create an imaginary number, and we only need real numbers.
If (b ^ 2) - (4 * a * c) < 0 Then
MsgBox ("The selected numbers for a, b, and c would make an imaginary number. Please try again.")
'If the selected values for abc do not create an imaginary number, the equation is run giving the two values of the x's.
Else
x1 = (-b + Sqr((b ^ 2) - (4 * a * c))) / (2 * a)
x2 = (b + Sqr((b ^ 2) - (4 * a * c))) / (2 * a)
'Msgbox showing the equation with the values for abc and the values for x1 and x2.
MsgBox (a & "(x^2)+" & b & "x+" & c & vbNewLine & "x1=" & x1 & vbNewLine & "x2=" & x2)
End If
End Sub
编辑:没关系。我换了负片。谢谢。
解决方案
包括检查虚数:
Sub main()
Dim a As Double
Dim b As Double
Dim c As Double
Dim x1 As Double
a = InputBox("Write a number for a")
b = InputBox("Write a number for b")
c = InputBox("Write a number for c")
If (b ^ 2) - (4 * a * c) < 0 Then
MsgBox "The square root of ((" & b & " ^ 2) - (4 * " & a & " * " & c & ")) = (" & (b ^ 2) - (4 * a * c) & ") would make an imaginary number."
Else
x1 = (-b + Sqr((b ^ 2) - (4 * a * c))) / (2 * a)
MsgBox x1
End If
End Sub
这是另一个替代方案:
使用 ImSqrt 以文本格式返回复数x + yi
的平方根x + yj
- 但它可能相当“复杂”。
推荐阅读
- apache-spark - 从列中查找 15 分钟的时间间隔
- python - 尝试更大的容器时,Python 中的 Quick_Sort 不起作用
- tkinter - 根据其内容更改选项卡的外观?
- javascript - setInterval - 'interval' 未定义
- apache-spark - Pyspark 驱动程序没有选择我的环境配置
- solr - 计算一个方面的所有值的不同分组文档
- regex - Erlang 中的正则表达式。在结果列表中添加其他匹配
- angular - 带有可选 api 调用的 rxjs
- r - 如何定义 R 中的“上升”和“下降”趋势?
- python - 如何在 dockerfile CMD 脚本中执行 npm start