gpt4 book ai didi

Excel 2010 : How do I formulaically count the total number of cells within a range that containts merged cells?

转载 作者:行者123 更新时间:2023-12-04 20:53:39 25 4
gpt4 key购买 nike

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

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

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

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

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

谢谢

最佳答案

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

关于Excel 2010 : How do I formulaically count the total number of cells within a range that containts merged cells?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52781949/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com