对于刚接触 VBA 的人来说,这是一项不错的工作,您的代码只需要一些调整。
首先是一行:
lastcol = Range("B5", Range("B5").End(xlToLeft)).Columns.Count + 1
基本上会找到范围“B5”区域的左端 - 最有可能是“A5” - 所以lastcol 将始终等于 3。
其次,行:
Range(ActiveCell, ActiveCell.Offset(0, i)).Value = ...
定义从ActiveCell 开始到该单元格的偏移值结束的范围。换句话说,根据i 的值,您将在该范围内拥有多个单元格,但ActiveCell 将始终是该范围内的第一个单元格。鉴于您的输出值是 double 而不是数组,您的代码会将该值写入范围内的每个单元格。所以你之前的计算总是会被覆盖。
还有一点需要注意的是,您应该始终使用工作表对象限定您的范围。在您的代码中,存在处理错误工作表的风险。我也避免使用ActiveCell 属性,因为选择错误,整个工作表可能会被搞砸。
值得使用 F8 单步执行您的代码,因为您可以看到分配给变量的值。我还喜欢在测试期间选择我的范围,以查看正在识别哪些单元格。也许您可以在未来的开发中采用这些做法。
总而言之,您的代码可能如下所示:
Dim lastCol As Long, i As Long
Dim rng As Range
'Find the last column.
'Assumes the relevant column is the last one with data in row 5.
With Sheet1
lastCol = .Cells(5, .Columns.Count).End(xlToLeft).Column
End With
'Iterate the columns from 1 (ie "A") to the last.
For i = 1 To lastCol
With Sheet1
'Define the data range for this column.
'Assumes last cell from bottom of sheet is the end of data.
Set rng = .Range(.Cells(5, i), .Cells(.Rows.Count, i).End(xlUp))
'Write the average to the cell above.
.Cells(4, i) = WorksheetFunction.Average(rng)
End With
Next