我正在尝试从单元格2到19中获取测试分数并将其设置为等于20.但是,当我输入代码时,它只打印出#NAME?
。如何修复它以确保打印平均分数?
Sub Scores()
Dim ws As Worksheet
Set ws = Worksheets("Sheet3")
ws.Activate
Dim rngStart As Range
Dim rngEnd As Range
Set rngStart = Range("A1").Cells(2, 5)
Set rngEnd = Range("A1").Cells(19, 5)
Dim MidtermAvg As Range
Set MidtermAvg = Range(rngEnd.Offset(1, 0), rngEnd.Offset(1, 0))
' Put in average at the bottom of the range
MidtermAvg.Formula = "=AVERAGE(rngEnd:rngStart)"
End Sub
以下分数列在一栏中:
63
44
87
96
67
82
58
71
61
77
63
30
93
38
89
89
93
93
答案 0 :(得分:3)
您错过了一些工作表参考,
并且您的公式将rngStart
和rngEnd
变量隐藏在字符串中
(VBA如何知道这些是变量?)
此外,您需要获取这些范围对象的.Address
这有效:
Sub Scores()
Dim ws As Worksheet
Set ws = Worksheets("Sheet3")
ws.Activate
Dim rngStart As Range
Dim rngEnd As Range
Set rngStart = ws.Range("A1").Cells(2, 5)
Set rngEnd = ws.Range("A1").Cells(19, 5)
Dim MidtermAvg As Range
Set MidtermAvg = ws.Range(rngEnd.Offset(1, 0), rngEnd.Offset(1, 0))
' Put in average at the bottom of the range
MidtermAvg.Formula = "=AVERAGE(" & rngStart.Address & ":" & rngEnd.Address & ")"
End Sub
答案 1 :(得分:1)
我不确定您为什么使用Range("A1")
然后使用Cells(r,c)
表示法来获取范围"E2:E19"
。如果分数在该范围内,那么为什么不如下:
Sub AverageScore()
Dim scores As Range
Set scores = Range("E2:E" & Range("E2").End(xlDown).Row)
Range("E" & scores.End(xlDown).Row).Offset(1, 0) = "Avg: " & Round(WorksheetFunction.Average(scores), 2)
End Sub
注意 - 我已经冒昧地将平均值四舍五入到2个小数点并添加一个标签,结果显示为Avg: 71.89
,但您可以根据需要进行更改。