首页 > 解决方案 > 不断收到运行时错误“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

编辑:没关系。我换了负片。谢谢。

标签: excelvba

解决方案


包括检查虚数:

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- 但它可能相当“复杂”。


推荐阅读