Sub for Simpson在Excel VBA中的1/3,但出现错误("需要对象")

时间:2015-04-12 01:07:37

标签: excel-vba vba excel

我正在为Simpson 1/3规则编写子代码。我有该功能的代码,但它不适用于我在Sub中需要做的小调整。 Sub必须使用SimpsonResultCell.Value来显示:

  • 消息(当点数不是奇数时)或
  • TheresultfromtheSimpson1 / 3equation。

要使用的信息是:"需要偶数个间隔(奇数个点)"

所以这是我的代码:

Sub Simpson13Sub()
    Dim xData As Range, yData As Range
    Dim x() As Double, y() As Double, h As Double, sum As Double
    Dim n As Integer, i As Integer, np As Integer, SimpsonResultCell As Integer

    Set xData = Application.InputBox("Select cell with x Data", Type:=8)
    Set yData = Application.InputBox("Select cell with y Data", Type:=8)
    Set SimpsonResultCell = Application.InputBox("Select cell to display result", Type:=8) ' object required appears here
    np = xData.Count 'number of points
    n = np - 1 'number of intervals

    If (n Mod 2 <> 0) Then
        SimpsonResultCell = "An even number of intervals is necessary (odd number of points)"
        Exit Sub
    Else
        Do
            ReDim x(0 To n)
            ReDim y(0 To n)
            For i = 0 To n
                x(i) = xData(i + 1)
                y(i) = yData(i + 1)
            Next i
                sum = y(0) + y(n)
            For i = 1 To n - 1 Step 2
            sum = sum + 4 * y(i)
            Next i
            For i = 2 To n - 2 Step 2
                sum = sum + 2 * y(i)
            Next i
                h = (x(n) - x(0)) / n
                SimpsonResultCell = h * sum / 3
        Exit Do
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

您的错误来自此声明:

SimpsonResultCell As Integer

这项任务:

Set SimpsonResultCell = Application.InputBox("Select cell to display result", Type:=8)

语法Set Foo = Application.InputBox返回一个Range对象。您正在尝试将其分配给整数。您需要做的就是使用正确的Dim语句:

Dim SimpsonResultCell As Range