EXCEL VBA-平均包含合并区域中每列的数值的所有行

时间:2013-07-02 15:41:44

标签: excel vba excel-vba

我有多个电子表格,每个电子表格大致如下所示:

enter image description here

我正试图找到一种方法来浏览第1行中的每个SPEAKER HEADERS,并总结与相应调查问题相关的分数(“内容是否良好?SPEAKER是否相关?什么是交付?好吗?)按颜色分组。

我无法想到一种自动执行此操作的聪明方法。

我可以像这样得到合并细胞的RANGE SPANS:

  For Each Cell In src_sheet.UsedRange.Cells
        If Cell.Row = 1 And IsEmpty(Cell) = False Then
            MsgBox Cell.MergeArea.Address
        End If
    Next

然后我需要迭代地址提供的范围,获得该范围以下所有行的数值。

例如,运行当前宏会产生以下结果:

enter image description here

我需要取$C$1:$E$1并运行一个for循环,说明FROM C1到E1平均下面行中的所有数字。我不知道如何做到这一点。

我在考虑增加包含所用内容的选择

有更好的方法吗?

这是我现在正在做的悲惨的糟糕方式(我为excel新手而感到自豪):

    For Each Cell In src_sheet.UsedRange.Cells
        If Cell.Row = 1 And IsEmpty(Cell) = False Then
            Set rng = Range(Cell.MergeArea.Address) 'Equal to the Address of the Merged Area
            startLetter = Mid(rng.Address, 2, 1)  'Gets letter from MergeArea Address
            endLetter = Mid(rng.Address, 7, 1) 'Gets letter from MergeArea Address

            On Error GoTo ErrHandler:
                Set superRange = Range(startLetter & ":" & endLetter)

ErrHandler:
    endLetter = startLetter
    Set superRange = Range(startLetter & ":" & endLetter)
Resume Next

            superRange.Select
            MsgBox Application.Average(Selection) 

1 个答案:

答案 0 :(得分:2)

为了摆脱您所遇到的错误,您需要更改:

Set rng = Cell.MergeArea.Address

Set rng = Range(Cell.MergeArea.Address)

理想情况下,这些数据可以更好地存储在数据库中,以便可以轻松查询。如果这不是一个选项,那么你在Excel中使用它的方式与大多数其他方法一样有效。

修改

获得每个发言者最左列的地址后,您可以遍历每一列以获得平均值。

'Number of columns in the current speaker's range.
numColumns = rng.Columns.Count
'First row containing data.
currentRow = 4
'First column containing data.
firstColumn = rng.Column
'Loop through each column.
For col = firstColumn to firstColumn + (numColumns -1)
  totalValue = 0
  'Loop through each row.
  Do While Cells(currentRow,col).value <> ""
    totalValue = totalValue + Cells(currentRow,col).Value
    currentRow = currentRow + 1
  Loop
  averageValue = totalValue / (currentRow - 3)
  'Reset the currentRow value to the top of the data area.
  currentRow = 4
  'Do something with this average value before moving on to the next column.
Next

如果您不知道数据的开头是哪一行,您可以继续检查rng.Row下面的每一行,直到您点击数值。

上述方法假设您的数据区中没有空白条目。如果您有空白条目,那么您应该在运行此代码之前对数据进行排序,或者您需要知道必须检查数据值的行数。