我有一个表格,第一行是标题,第一列是学生姓名,其余的单元格有不同的学生分数。
我必须在列O上创建一个名为Average Score的新标题。完成后,我必须计算从列B到列N的所有值,然后打印出列O的每一行的平均值。
Sub CalculateAverage()
Dim rng As Range
Dim totalsum As Double
Dim totalnum As Double
Dim answer As Double
totalsum = 0
totalnum = 0
Set rng = Cells(1, 1).CurrentRegion
For Each Sheet In Application.Worksheets
Sheet.Cells(1, 15) = "Average Score"
ActiveSheet.Cells.HorizontalAlignment = xlLeft
Next
For Each Sheet In Worksheets("Sheet1").Range("B2:N502").Cells
totalsum = totalsum + Sheet.Value
totalnum = totalnum + 1
Next
answer = totalsum / totalnum
Average = answer
Range("O2").Select
ActiveCell.FormulaR1C1 = Average()
End Sub
我在最后一行收到调试错误。任何人都可以帮我解决这个问题。感谢
答案 0 :(得分:0)
如果我这样做,我会将数据取消,从中制作数据透视表,并使用数据透视表。如果我安装了插件,我会使用PowerQuery来执行此操作(并且它已经在Excel 2016中进行了烘焙)。否则,我会在convert cross table to list to make pivot table的答案中使用其中一种方法,然后我只需启动宏录制器,制作枢轴,然后查看并修改生成的代码。
答案 1 :(得分:0)
Sub Macro1()
Dim rng As Range
Set rng = Range("A1").CurrentRegion
With Range("O2")
.Formula = "=AVERAGE(RC[-13]:RC[-1])"
.AutoFill Destination:=Range("O2:O" & rng.Rows.Count)
End With
End Sub