从另一个范围名称

时间:2017-07-25 08:25:44

标签: vba excel-vba excel

我是excel VBA的新手。我正在尝试在我的工作簿中创建一个函数,它将执行excel linest函数。我有一个范围(pqr),其中第一列是Y变量,第二列是X变量。我想在代码中将R1和R2分配为变量。我试图从其他线程获取代码,但下面是我写的代码......

Function LinestTest(pqr As Range)
 Dim vCoeff As Variant
 Dim r1 As Range
 Dim r2 As Range
 Set r1 = Range(pqr).Offset(, 1)
 Set r2 = Range(pqr).Offset(, 0)
 vCoeff = WorksheetFunction.LinEst(r1, Application.Power(r2, Array(1, 2, 3)))
 LinestTest = vCoeff

如果我分别传递r1和r2,则代码可以正常工作。

2 个答案:

答案 0 :(得分:1)

由于pqr定义为Range,您需要直接在其上应用Offset属性。

替换:

Set r1 = Range(pqr).Offset(, 1)
Set r2 = Range(pqr).Offset(, 0)

使用:

Set r1 = pqr.Offset(, 1)
Set r2 = pqr.Offset(, 0)

B.T.W

Set r2 = pqr.Offset(, 0)相当于Set r2 = pqr

答案 1 :(得分:0)

这就算了......

    Function LinestTest(pqr As Range)
    Dim vCoeff As Variant
    Dim r1 As Range
    Dim r2 As Range
    'Set r1 = pqr.Offset(, 1)
    'Set r2 = pqr.Offset(, 2)
    Set r2 = pqr.Offset(0, 0).Resize(pqr.Rows.Count, pqr.Columns.Count - 1)
    Set r1 = pqr.Offset(0, 1).Resize(pqr.Rows.Count, pqr.Columns.Count - 1)

    vCoeff = WorksheetFunction.LinEst(r1, Application.Power(r2, Array(1, 2, 3)))
    LinestTest = vCoeff
End Function