等式来求解x

我有一个string中的以下公式

y = 18774x + 82795 

解决x我会这样做: –

 x = (y-82795) / 18774 

我知道y的价值

然而公式总是改变,并且总是以string格式

是否有可能简单地将原始公式抛出在Evaluate语句中并自动求解x?

我知道我可以做这样的事情:

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

但在我看来,这将是

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

其中y = 67657657

这显然会引发一个错误。 有一个简单的方法,我可以解决x

否则,我将需要parsing的string,并更加手动

A1放置string:

y = 18774x + 82795

A2中放置y值:

 67657657 

然后试试这个macros:

 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 

尝试这个:

 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 

鉴于你正在解决一个线性方程:

 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