【问题标题】:Excel 2010: How do I formulaically count the total number of cells within a range that containts merged cells?Excel 2010:如何以公式方式计算包含合并单元格的范围内的单元格总数?
【发布时间】:2019-03-17 19:52:28
【问题描述】:

我一直在使用=ROWS(my_range)*COLUMNS(my_range) 来计算单列中的单元格总数。

我现在正在尝试计算包含(不可避免地)合并单元格的范围内的单元格总数,并且使用上面的公式得到#REF 错误。

我也试过:=COUNTA(my_range) & "/" & COUNTA(my_range) + COUNTBLANK(my_range) 这给了我一个#VALUE! 错误。

在我最后一次尝试中,我希望=ROWS(my_range) 可以工作,因为我只有合并的列,而不是合并的行。然而,这给了我一个#REF 错误。 `

我只需要my_range中存在的单元格总数

谢谢

【问题讨论】:

  • 为什么引号:& "/" & 只使用/
  • 这给了我一个DIV/0! 错误,这是我以前从未见过的。我不知道错误会像那样分裂。
  • =COUNTA(my_range) /(COUNTA(my_range) + COUNTBLANK(my_range))
  • 无法重现错误 - my_range 所指的区域是什么?
  • @L23P 实际地址是什么?如果my_range 有多个区域,COUNTBLANK 将返回 #VALUE! 错误。

标签: excel excel-formula excel-2010


【解决方案1】:

所以使用合并的单元格会使处理大量公式变得非常烦人,所以我使用数组编写了一个 VBA 解决方案:

首先,此函数将遍历范围,每次识别合并单元格时,代码会将单元格添加到数组中。

稍后当循环到达标记为“合并”的单元格(= 在数组中)时,计数将跳过它(感谢此主题:Check if a value is in an array or not with Excel VBA)。

Option Explicit

Function CountCells(RA As Range) As Long

Application.Volatile

    Dim i As Long
    Dim a As Long
    Dim i2 As Long
    Dim a2 As Long
    Dim RowCount As Long
    Dim ColCount As Long
    Dim k As Long
    Dim R1 As Long
    Dim R2 As Long
    Dim C1 As Long
    Dim C2 As Long
    ReDim iArray(1 To 1) As Variant

R1 = RA.Row
R2 = R1 + RA.Rows.Count - 1
C1 = RA.Column
C2 = C1 + RA.Columns.Count - 1

k = 0

    For i = R1 To R2
        For a = C1 To C2

                If IsInArray(Cells(i, a).Address, iArray) Then
                    GoTo next_a
                End If

            ColCount = Cells(i, a).MergeArea.Columns.Count
            RowCount = Cells(i, a).MergeArea.Rows.Count

                If RowCount > 1 Or ColCount > 1 Then
                    k = k + RowCount * ColCount - 1

                    For i2 = i To i + RowCount - 1
                        For a2 = a To a + ColCount - 1
                            iArray(UBound(iArray)) = Cells(i2, a2).Address
                            ReDim Preserve iArray(1 To UBound(iArray) + 1) As Variant
                       Next a2
                    Next i2

                End If
next_a:
        Next a
    Next i

    CountCells = (R2 + 1 - R1) * (C2 + 1 - C1) - k

End Function


Public Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
Application.Volatile
    Dim i
    For i = LBound(arr) To UBound(arr)
        If arr(i) = stringToBeFound Then
            IsInArray = True
            Exit Function
        End If
    Next i
    IsInArray = False

End Function

那么你只需要在你的工作表中像这样使用这个函数:

=countcells(my_range) 

或任何其他范围,而不是名为 my_range 的范围

注意:使用Application.Volatile,函数会自动更新,但仅在您使用数字更新工作表时才会更新,而不是在合并或取消合并单元格时直接更新。

【讨论】:

  • 谢谢@Pierre44 我现在就试试这个,叫我笨,但我是在普通模块中使用它还是需要去其他地方?
  • 在相关工作簿的普通模块中很好:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-28
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-19
相关资源
最近更新 更多