我试图在VBA中获得三阶LinEst函数。但是,当达到Ubound(xl)时,错误总是以预期数组的形式出现。
Option Explicit
Sub RB()
Dim xl As Range, e As Double
Dim yl As Range, s As Variant
Dim X
With ThisWorkbook.Worksheets("Sheet1")
Set yl = .Range(.Cells(17, 7), .Cells(93, 7))
Set xl = .Range(.Cells(17, 1), .Cells(93, 1))
ReDim arrX3(1 To UBound(xl), 1 To 3) As Double
For i = LBound(xl) To UBound(xl)
arrX2(i, 1) = xl(i, 1)
arrX2(i, 2) = xl(i, 1) * xl(i, 1)
arrX2(i, 3) = xl(i, 1) * xl(i, 1) * xl(i, 1)
Next
X = Application.LinEst(yl, arrX3)
.Range(.Cells(12, 12), .Cells(15, 14)).Value = Application.Transpose(X)
End With
End Sub
答案 0 :(得分:1)
Option Base 1
Option Explicit
Sub RB()
Dim xl As Range, e As Double
Dim yl As Range, s As Variant
Dim X As Variant, i As Long
e = 76
With ThisWorkbook.Worksheets("Sheet1")
Set yl = .Range(.Cells(17, 7), .Cells(e - 1, 7))
Set xl = .Range(.Cells(17, 1), .Cells(e - 1, 1))
Debug.Print "First row in xl is " & xl.Row
Debug.Print "Range xl has " & xl.Rows.Count & " rows"
Debug.Print "Last row in xl is " & xl.Rows.Count + xl.Row - 1
ReDim arrX3(1 To xl.Rows.Count, 1 To 3) As Double
For i = 1 To xl.Rows.Count
arrX3(i, 1) = xl.Cells(i, 1)
arrX3(i, 2) = xl.Cells(i, 1) * xl.Cells(i, 1)
arrX3(i, 3) = xl.Cells(i, 1) * xl.Cells(i, 1) * xl.Cells(i, 1)
Next i
X = Application.LinEst(yl, arrX3)
.Range(.Cells(12, 12), .Cells(15, 14)).Value = Application.Transpose(X)
End With
End Sub
是一个范围,而不是是一个数组。因此,Debug.Print
将不起作用。虽然我不明白你的代码是想要实现的,但我相信你正在寻找像这样的东西:
{{1}}
请注意,我添加了一些您可能需要查看的{{1}}。
答案 1 :(得分:0)
xl
被声明为范围,范围没有Ubound
。
将xl
的声明从Range
更改为Variant
并替换
Set xl = .Range(.Cells(17, 1), .Cells(93, 1))
通过
xl = .Range(.Cells(17, 1), .Cells(93, 1)).Value
我不确定这是否足以使您的代码按预期运行,但它至少会消除您描述的错误。