【问题标题】:Excel vba - calculate average of data with a dynamic number of columnsExcel vba - 计算具有动态列数的数据平均值
【发布时间】:2019-06-10 11:46:08
【问题描述】:

我是 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 列中数据的平均值。我想计算有数据的每一列的平均值,并将该值放入没有任何数据的第一行。

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    对于刚接触 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
    

    【讨论】:

      【解决方案2】:

      首先,您可以使用 for each 循环来遍历单元格,并使用 usedRange 属性获取已使用的单元格。

      usedRange

      For Each

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-03
        相关资源
        最近更新 更多