我不懂 R,所以我不能确切地告诉你要做什么,但 Excel 有多种回归分析的功能。
SLOPE() 函数将为您提供斜率 b(我认为这就是您所说的“系数”),INTERCEPT() 函数将为您提供 y 截距 a (我认为这就是你所说的“常数”)。还有LINEST() 函数可以返回可能对您有用的各种统计信息(请参阅https://support.office.com/en-us/article/linest-function-84d7d0d9-6e50-4101-977a-fa7abf772b6d)
直接输入到电子表格中的任何这些 Excel 函数都将返回您可能需要的值,而无需使用 VBA。但是,下面是获取相同统计信息的 VBA 代码。这不是管理数据的最有效方式,但我不确定您在 Excel-VBA 方面的经验水平,所以我尽量让代码简单易懂。您可能需要根据您的需要使用LinEst 结果,您可以通过将最后一个参数更改为True 来绘制其他数据(请注意,返回数组将变为二维,因此您需要更改下面给出的常量):
Const COEFFICIENT_b As Long = 1
Const CONSTANT_a As Long = 2
Dim ws As Worksheet
Dim firstRow As Long, lastRow As Long, r As Long
Dim groupFirstRow As Long, groupLastRow As Long
Dim colGrp As Long, colX As Long, colY As Long, colB As Long, colA As Long
Dim groupID As Long
Dim rngX As Range, rngY As Range
Dim result As Variant
'Define range parameters
Set ws = ThisWorkbook.Worksheets("Sheet1") 'set this to your sheet object
firstRow = 2
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
colGrp = 1
colX = 2
colY = 3
colB = 4
colA = 5
'Set the group values to first item
groupID = ws.Cells(firstRow, colGrp).Value2
groupFirstRow = firstRow
For r = firstRow + 1 To lastRow
'Check for a new group.
If ws.Cells(r, colGrp).Value2 <> groupID Or r = lastRow Then
'Set the row limit for this group.
groupLastRow = IIf(r = lastRow, r, r - 1)
'Set the X and Y data ranges.
Set rngY = ws.Range(ws.Cells(groupFirstRow, colY), ws.Cells(groupLastRow, colY))
Set rngX = ws.Range(ws.Cells(groupFirstRow, colX), ws.Cells(groupLastRow, colX))
'Call the LinEst function.
result = WorksheetFunction.LinEst(rngY, rngX, True, False)
'Write the results to the sheet.
ws.Cells(groupFirstRow, colB) = result(COEFFICIENT_b)
ws.Cells(groupFirstRow, colA) = result(CONSTANT_a)
'Reset the groupId and row variables
groupID = ws.Cells(r, colGrp).Value2
groupFirstRow = r
End If
Next