求解x的方程式

时间:2014-05-05 12:28:06

标签: excel vba

我在字符串中有以下等式

y = 18774x + 82795

解决x我会这样做: -

x = (y-82795) / 18774

我知道y

的价值

然而,等式一直在变化,并且始终采用字符串格式

是否可以简单地将原始等式抛出到Evaluate语句并让它自动求解x?

我知道我可以这样做: -

MsgBox Evaluate("5*(8+3)-2*(3*5)")

但在我的情况下,它将是

MsgBox Evaluate("67657657 = 18774x + 82795") 

其中y = 67657657

这显然会引发错误。我能为x解决一个简单的方法吗?

否则我需要解析字符串并更多地手动处理

3 个答案:

答案 0 :(得分:2)

试试这个:

Public Function SolveEquation(ByVal eq As String) As Double
    Dim i_eq As Integer, y As Double
    ' eq : "67657657 = 18774x+82795"
    i_eq = InStr(1, eq, "=")
    y = 0#
    If i_eq > 0 Then
        y = Application.Evaluate(Trim(Left(eq, i_eq - 1)))
        'y =67657657
        eq = Trim(Mid(eq, i_eq + 1))
    End If

    Dim eq_1 As String, eq_2 As String
    Dim x_1 As Double, x_2 As Double
    Dim y_1 As Double, y_2 As Double
    x_1 = 0#: x_2 = 1#
    eq_1 = Replace(eq, "x", "*(" & CStr(x_1) & ")")
    y_1 = Application.Evaluate(eq_1)
    eq_2 = Replace(eq, "x", "*(" & CStr(x_2) & ")")
    y_2 = Application.Evaluate(eq_2)
    ' y_1 = 82795, y_2 = 101569

    ' Alternative solution from evaluation points
    ' SolveEquation = x_1 + (x_2-x_1)/(y_2-y_1)*(y-y_1)

    ' y = a*x+b
    Dim a As Double, b As Double
    a = (y_2 - y_1) / (x_2 - x_1)
    b = y_1 - a * x_1
    ' a= 18774, b = 82795

    ' Solution from linear form y = a*x+b
    SolveEquation  = (y - b) / a
    ' 3599.38542665388

End Function

答案 1 :(得分:1)

A1 中放置字符串:

y = 18774x + 82795

A2 中放置y值:

67657657

然后试试这个宏:

Sub Zolver()
    Dim sTr As String, X As Double
    Dim A As Double, B As Double, Y As Double
    sTr = Range("A1").Value
    sTr = Replace(sTr, " ", "")
    sTr = Replace(sTr, "x", "")
    sTr = Replace(sTr, "y=", "")
    sTr = Replace(sTr, "+", ",")
    A = CDbl(Split(sTr, ",")(0))
    B = CDbl(Split(sTr, ",")(1))
    Y = CDbl(Range("A2").Value)
    X = (Y - B) / A
    MsgBox X
End Sub

答案 2 :(得分:0)

鉴于您正在求解线性方程:

Sub Extract()
Dim strFunc As String
Dim X(1 To 2) As Variant
Dim Y(1 To 2) As Variant
Dim C As Variant
X(1) = 0
X(2) = 100
strFunc = "18774x + 82795"
Y(1) = Evaluate(Replace(LCase$(strFunc), "x", X(1)))
Y(2) = Evaluate(Replace(LCase$(strFunc), "x", X(2)))
C = Application.WorksheetFunction.LinEst(Y, X)
MsgBox "K is " & C(1) & vbNewLine & "M is " & C(2)
End Sub