使用等式作为VBA函数输入的一部分?

时间:2016-04-05 03:03:59

标签: excel vba excel-vba

我目前正在为我的某个工程类的实验室编写VBA代码。目标是使用单个函数来近似(梯形法则)给定方程的积分。等式需要在某个时刻改变。我是编程新手,所以我计划看到某种简单的逻辑错误。这就是我目前所拥有的:

Function Trapezoidal(ByVal sFx As String, ByVal A As Double, _
 ByVal B As Double, ByVal N As Integer) As Double
' Calculates the area under the curve using the Trapezoidal rule.
'
' Parameters:
'
' sFx - String expression that has the function to be
' integrated. The variable X as to appear as $X.
' An example is: $X*LOG(X$) which is an expression for function
' f(x)=x*ln(x)
' A, B - Lower and Upper limit for the integral.
' N - The number of integration intervals.
'
 Dim Sum As Double, DeltaX As Double, X As Double
 Dim I As Integer

Sum = 0
 DeltaX = (B - A) / N
 X = A
 For I = 1 To N
 Sum = Sum + (Fx(sFx, X) + Fx(sFx, X + DeltaX)) / 2
 X = X + DeltaX
 Next I
 Sum = DeltaX * Sum
 Trapezoidal = Sum
End Function

在我的研究中,我已经将几段代码拼凑在一起。显然不是什么

1 个答案:

答案 0 :(得分:1)

Sub Tester()
    Debug.Print Trapezoidal("$X*LN($X)", 1, 20, 5)
End Sub


Function Trapezoidal(ByVal sFx As String, ByVal A As Double, _
                    ByVal B As Double, ByVal N As Integer) As Double
    ' Calculates the area under the curve using the Trapezoidal rule.
    '
    ' Parameters:
    '
    ' sFx - String expression that has the function to be
    ' integrated. The variable X as to appear as $X.
    ' An example is: $X*LOG(X$) which is an expression for function
    ' f(x)=x*ln(x)
    ' A, B - Lower and Upper limit for the integral.
    ' N - The number of integration intervals.
    '
    Dim Sum As Double, DeltaX As Double, X As Double
    Dim I As Integer, f As String

    Sum = 0
    DeltaX = (B - A) / N
    X = A
    For I = 1 To N
        'Sum = Sum + (Fx(sFx, X) + Fx(sFx, X + DeltaX)) / 2
        f = "(" & Replace(sFx, "$X", X) & " + " & Replace(sFx, "$X", X + DeltaX) & ")/2"
        Debug.Print f
        Sum = Sum + Application.Evaluate(f)
        X = X + DeltaX
    Next I
    Sum = DeltaX * Sum
    Trapezoidal = Sum
End Function

调试输出:

(1*LN(1) + 4.8*LN(4.8))/2
(4.8*LN(4.8) + 8.6*LN(8.6))/2
(8.6*LN(8.6) + 12.4*LN(12.4))/2
(12.4*LN(12.4) + 16.2*LN(16.2))/2
(16.2*LN(16.2) + 20*LN(20))/2
 502.848119401941