首页 > 解决方案 > Excel 2010:如何公式计算包含合并单元格的范围内的单元格总数?

问题描述

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

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

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

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

我所需要的只是其中存在的细胞总数my_range

谢谢

标签: excelexcel-formulaexcel-2010

解决方案


所以使用合并的单元格使得处理很多公式真的很烦人,所以我用数组写了一个 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功能会自动更新,但仅当您使用数字更新工作表时,而不是在合并或取消合并单元格时直接更新。


推荐阅读