2016-04-09 161 views
4

我試圖在VBA中獲得第三個LinEst函數。但是,當它到達Ubound(xl)時,該錯誤總是作爲Expected數組出現。如何在VBA中應用Linest功能?

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

它沒有工作。 – Rain

回答

1

xl是一個範圍和而不是一個數組。因此,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,你可能希望有一看。

+0

謝謝。有用! – Rain

0

xl被宣佈爲一個範圍,範圍內沒有Ubound

變化xlRange的聲明Variant和更換線

Set xl = .Range(.Cells(17, 1), .Cells(93, 1)) 

通過

xl = .Range(.Cells(17, 1), .Cells(93, 1)).Value 

我不知道這是否會是足以讓你的代碼運行符合預期,但它至少會擺脫你描述的錯誤。