使用数学方程式输入值在 VBA Excel 中进行数学计算

Use math equation input value to do math calculation in VBA Exccel

我在 Excel VBA 中进行数值积分,我想从用户那里获取方程而不是将其插入到 Cell 中。

例子

用户给我x^3+x^2+2 也就是F(X)

在 A1 中,我有数字 2,我在 B1 中评估 F(X)。

如何告诉excel用户输入的方程是=A1^3+A2^2+2。我只需要转换为一个单元格。

我正在使用 Val(InputBox())

感谢帮助

Application Evaluate 函数可以解析从用户那里收到的公式,但您必须想办法将 x 转换为可以正确理解的单元格引用。这可能需要工作表名称。

您的 x^3+x^2+2 示例将两个 x 值替换为 A1 和 A2。它可能更好 x^3+y^2+2 这样 A1 和 A2 之间就没有歧义了。

Sub f_of_x_and_y()
    Dim fmla As String, str As String

    fmla = InputBox("enter formula")

    With Worksheets("Sheet2")
        str = Replace(Replace(fmla, "x", .Range("A1").Address(external:=True)), _
                                    "y", .Range("A2").Address(external:=True))
        .Range("A3") = Application.Evaluate(str)
    End With

End Sub

如果用户输入 x 或 X 而你只需要将 X 替换为 A1.cell.value 则使用此:

Sub test()
formula_user = InputBox("Please type formula")
Range("B1").Formula = "=" & Replace(LCase(formula_user), "x", "A1")
End Sub

x 替换为用户输入框中公式中的 A1。用户输入可大写或小写

Sub variable_input()
Dim userFormula$
Dim myVar&

myVar = 2
userFormula = InputBox("What is the formula?")
Debug.Print userFormula
userFormula = Replace(userFormula, "x", myVar)
Debug.Print userFormula

Dim theAnswer$
theAnswer = Val(userFormula)
Debug.Print theAnswer
End Sub

您可以将所有 "x" 替换为字符串 "A1"。不要忘记在前面加上“=”...

Sub TestUserEquation()

    Dim strUserEquation As String

    strUserEquation = LCase(InputBox("Please enter your equation:", "Equation InputBox"))

    If strUserEquation <> "" Then
        Cells(1, 2) = "=" & Replace(strUserEquation, "x", "A1")
    Else
        Cells(1, 2) = "No equation entered."
    End If


End Sub