我试图编写一个包含平均一系列单元格的行的短宏。在我想要运行的每个工作表中,单元格范围内的宏是不同的长度。
运行宏后,单元格E1包含"=AVERAGE(Rng)"
Dim homeSheet As Worksheet
Set homeSheet = ActiveSheet
Dim lastRow As Long
Dim Rng As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("B2:B" & lastRow)
Range("E1").Formula = "=Average(Rng)"
Range("E2").Formula = "=STDEV(Rng)"
Range("E3").Select
ActiveWindow.SmallScroll Down:=-2
End Sub
我也试过
Range("E1").Formula = "=Average(Range("B2:B" & lastRow))"
不试图使用Set Rng = Range("B2:B" & lastRow)
答案 0 :(得分:1)
您需要在公式中使用Rng.Address
。尝试将您的代码更改为:
Sub Avg()
Dim homeSheet As Worksheet
Set homeSheet = ActiveSheet
Dim lastRow As Long
Dim Rng As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row
Set Rng = Range("B2:B" & lastRow)
Range("E1").Formula = "=Average(" & Rng.Address & ")"
Range("E2").Formula = "=STDEV(" & Rng.Address & ")"
Range("E3").Select
End Sub
如果您要使用您尝试过的第二种方法,则需要将该行代码更改为:
Range("E1").Formula = "=Average(" & Range("B2:B" & lastRow).Address & ")"