首页 > 解决方案 > VBA:对每行最右边的单元格求和?

问题描述

我有一个类似于下面的数据集。

我只想平均最右边一列中的数据。

C4我的范围从行或列 开始,没有设定的结束。

**1** 
1 **2** 
1 2 **3** 
1 **2**
**1**

我已经将以下内容放在一起,它可以为单个固定列执行我需要它执行的操作,但我不知道如何将其扩展为始终使用最右侧列中的值。

Dim Sum, Count As Integer

       Count = 0
       Sum = 0

    Application.ScreenUpdating = False

       Range("C4").Select
       Do While ActiveCell.Value <> ""

           Sum = Sum + ActiveCell.Value
           Count = Count + 1
           ActiveCell.Offset(1, 0).Activate

       Loop

       Range("O1").Value = Sum / Count

谢谢你。

标签: excelvba

解决方案


这将循环行。

MATCH 将返回最后一列的列号,其中包含一个数字。

然后我们在该列中获取该行的数字并将其添加到数组中。

然后在循环之后我们平均数组。

Sub aver()
    With Worksheets("Sheet4") 'Change to your sheet
        Dim lastrw As Long
        lastrw = .Cells(.Rows.Count, 3).End(xlUp).Row

        Dim num() As Variant
        ReDim num(1 To lastrw) As Variant

        Dim i As Long
        For i = 4 To lastrw
            Dim j As Long

            j = Application.Match(1E+99, Rows(i), 1)
            num(i) = .Cells(i, j).Value

        Next i

        .Range("O1").Value = Application.Average(num)
    End With
End Sub

推荐阅读