我有一份由12张纸组成的Excel文件 每张工作表都包含大量数据,范围从A列到X,行数可变 我试图计算每张纸的每列的平均值和标准误差。最好在摘要表上输出。
我的思考过程:
这是我尝试的代码,适用于在列中最后一个值的正下方生成的平均值。
Sub ColumnAverageFormula()
For i = 3 To 24
Columns(Columns(i).Address).Select
Cells(1, ActiveCell.Column).End(xlDown).Offset(1, 0).Formula = "=Average(" & Cells(1, ActiveCell.Column).Address(0, 0) & ":" & Cells(1, ActiveCell.Column).End(xlDown).Address(0, 0) & ")"
Next i
For j = 3 To 24
Columns(Columns(j).Address).Select
Cells(1, ActiveCell.Column).End(xlDown).Offset(1, 0).Formula = "=stdev.p(" & Cells(1, ActiveCell.Column).Address(0, 0) & ":" & Cells(1, ActiveCell.Column).End(xlDown).Address(0, 0) & ")"
Next j
End Sub
Tl;博士:我想写一些代码来计算我的Excel文件中每个工作表的每一列的平均值和标准误差,结果应该在一个'摘要&#39上生成;片材。
答案 0 :(得分:2)
您插入的公式引用了从第1行开始的范围。通常,您所描述的数据集在第一行中具有某种基于文本的列标题标签。如果是这种情况,您可能希望从第2行开始,而不是从第1行开始。以下从第1行开始。
Sub ColumnAverageFormula()
Dim c As Long, sr As Long
With Worksheets("Sheet1")
sr = .Cells(Rows.Count, 3).End(xlUp).Row
For c = 3 To 24
.Cells(sr + 1, c).Formula = "=average(" & .Range(.Cells(1, c), .Cells(sr, c)).Address(0, 0) & ")"
.Cells(sr + 2, c).Formula = "=stdev.p(" & .Range(.Cells(1, c), .Cells(sr, c)).Address(0, 0) & ")"
Next c
End With
End Sub
'as an alternate, you might consider putting all of the formulas in at once
Sub ColumnAverageFormula()
Dim c As Long, sr As Long
With Worksheets("Sheet1")
sr = .Cells(Rows.Count, 3).End(xlUp).Row
.Cells(sr + 1, 3).Resize(1, 22).Formula = "=average(" & Range(.Cells(1, 3), .Cells(sr, 3)).Address(0, 0) & ")"
.Cells(sr + 2, 3).Resize(1, 22).Formula = "=stdev.p(" & Range(.Cells(1, 3), .Cells(sr, 3)).Address(0, 0) & ")"
End With
End Sub
如果您想从第2行开始,请将.Range(.Cells(1, c), ...
更改为.Range(.Cells(2, c), ...
。