Excel vba-使用动态列数计算数据的平均值

Excel vba-使用动态列数计算数据的平均值,excel,vba,Excel,Vba,我是excel VBA新手,我想计算包含数据的每列的平均值 但是列的数量可能会根据用户复制和粘贴的数据的列数而变化 以下是我目前掌握的情况: Dim lastcol As Long Dim i As Integer lastcol = Range("B5", Range("B5").End(xlToLeft)).Columns.Count + 1 For i = 0 To lastcol Range(ActiveCell, ActiveCell.Offset(0, i)).Value =

我是excel VBA新手,我想计算包含数据的每列的平均值

但是列的数量可能会根据用户复制和粘贴的数据的列数而变化

以下是我目前掌握的情况:

Dim lastcol As Long
Dim i As Integer

lastcol = Range("B5", Range("B5").End(xlToLeft)).Columns.Count + 1

For i = 0 To lastcol

Range(ActiveCell, ActiveCell.Offset(0, i)).Value = 
Application.WorksheetFunction.Average(Range(Range("B5").Offset(0, i), 
Range("B5").Offset(0, i).End(xlDown)))

Next i

但这似乎只计算B列中数据的平均值。我想计算每个有数据的列的平均值,并将该值放入第一行中,而不包含任何数据。

首先,您可以使用a for each循环遍历单元格以及使用usedRange属性可以获得的已用单元格


我将Microsoft文档链接到它们,通过它们的组合,您应该能够导航到包含内容的每个单元格。

对于VBA新手来说,这是一项很好的工作,您的代码只需要进行一些调整

首先,线路:

lastcol = Range("B5", Range("B5").End(xlToLeft)).Columns.Count + 1
Range(ActiveCell, ActiveCell.Offset(0, i)).Value = ...
基本上会找到范围B5区域的左端-最有可能是A5-所以lastcol始终等于3

第二,线路:

lastcol = Range("B5", Range("B5").End(xlToLeft)).Columns.Count + 1
Range(ActiveCell, ActiveCell.Offset(0, i)).Value = ...
定义从ActiveCell开始到该单元格偏移值结束的范围。换句话说,根据i的值,在该范围内有许多单元格,但ActiveCell始终是该范围内的第一个单元格。假设输出值是双精度的而不是数组,那么代码将把该值写入范围内的每个单元格。因此,您以前的计算总是被覆盖

还需要注意的是,应始终使用图纸对象限定范围。在代码中存在处理错误工作表的风险。我也会避免使用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