vba - 如何在VBA中应用Linest函数?

标签 vba excel

我试图在 VBA 中获取三阶 LinEst 函数。然而,当到达 Ubound(xl) 时,错误总是以 Expected array 的形式出现。

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

最佳答案

xl 是一个 Range,不是 一个数组。因此,Ubound(xl) 将不起作用。虽然我不明白你的代码想要实现什么,但我相信你正在寻找这样的东西:

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

关于vba - 如何在VBA中应用Linest函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521200/

相关文章:

vba - 如何定义变量中的数组大小

excel - 带有选择项目宏的组合框

json - 将 JSON 文件导入 MS Access 表

Python字典到xlsx中的列

excel vba SKYPE4COMLib 不适用于 Skype for Business (SfB)

php - 逐张从excel文件中提取数据。单工lsx

vba byref 参数引用不可用

arrays - 更快地大范围修改(TextToDisplay)超链接的方法

excel - 如果将重复记录插入表中, Access 不会引发错误

Excel 2007 将工作表另存为 CSV 与在 VBA 中将工作表另存为 csv 不同