COUNTIF function 的字符串条件限制为 255 个字符。
来自support.office.com
长字符串返回错误值。 当您使用 COUNTIF 函数匹配长度超过 255 个字符的字符串时,它会返回不正确的结果。
support.office.com 在 COUNTIF 支持页面上提供了一个变通解决方案,但我无法让它工作,所以我编写了一个用户定义的函数,它可以工作,并添加了隐藏/可见和区分大小写的选项。
COUNTIFSBIGTXT function - 超过 255 个字符的标准字符串的 CountIfs 功能
将其放入公共模块代码表(alt+F11、Insert、Module)。
Option Explicit
Function COUNTIFSBIGTXT(iOptions As Long, ParamArray pairs()) As Long
'COUNTIFSBIGTXT - CountIfs functionality for criteria strings longer than 255 characters
' https://stackoverflow.com/questions/51688846#51689459
'
' =COUNTIFSBIGTXT(<options>, <string_range1>, <criteria1>, [string_range2], [criteria2], …)
' OPTIONS
' 0 No options
' +1 Include hidden cells in <string_range1>, [string_range2], etc
' +2 Case sensitive comparison
'throw error if string_range and criteria do not come in pairs
If Not CBool(UBound(pairs) Mod 2) Then
COUNTIFSBIGTXT = CVErr(xlErrValue)
Exit Function
End If
'declare variables
Dim i As Long, j As Long
Dim bIncludeHidden As Boolean, bCaseSensitive As Boolean
'set optional booleans
bIncludeHidden = CBool(1 And iOptions)
bCaseSensitive = CBool(2 And iOptions)
'restrict full column references to the parent worksheet's UsedRange
Set pairs(LBound(pairs)) = Intersect(pairs(LBound(pairs)), pairs(LBound(pairs)).Parent.UsedRange)
'resize all <string_range> to the same dimensions
With pairs(LBound(pairs))
For i = LBound(pairs) + 2 To UBound(pairs) Step 2
Set pairs(i) = pairs(i).Resize(.Rows.Count, .Columns.Count)
'Debug.Print pairs(i).Address(0, 0)
Next i
End With
'loop cell count in pairs(LBound(pairs)) for relative ordinal
For i = 1 To pairs(LBound(pairs)).Cells.Count
'loop through each pair of <string_range> and <criteria>
For j = LBound(pairs) To UBound(pairs) Step 2
'exit for if any argument pair does not meet criteria
With pairs(j).Cells(i)
'throw out worksheet error codes
If IsError(.Value) Then Exit For
'do the pair(s) meet a case insensitive match
If LCase(.Value2) <> LCase(pairs(j + 1)) Then Exit For
'do the pair(s) meet a case sensitive match with option
If .Value2 <> pairs(j + 1) And LCase(.Value2) = LCase(pairs(j + 1)) And bCaseSensitive Then Exit For
'are the cells visible or hidden with include option
If (.EntireRow.Hidden Or .EntireColumn.Hidden) And Not bIncludeHidden Then Exit For
End With
Next j
'determine if all argument pairs matched
If j > UBound(pairs) Then _
COUNTIFSBIGTXT = COUNTIFSBIGTXT + 1
Next i
End Function
Syntax:
=COUNTIFSBIGTXT(<options>, <string_range1>, <criteria1>, [optional string_range2], [optional criteria2], …)
Documentation
Sample data²
以下示例基于 9 行相同的 600 个字符的字符串,其中 3 行强制为大写。
Example 1
简单的 COUNTIF 操作丢弃过滤/隐藏的行并且不区分大小写。
=COUNTIFSBIGTXT(0, B:B, B2)
Example 2
扩展的 COUNTIFS¹ 操作丢弃过滤/隐藏的行但区分大小写的字符串比较。 A:A 的次要条件等于 A2 中的值。
=COUNTIFSBIGTXT(2, B:B, B2, A:A, A2)
¹ 失败时逻辑流“短路”。使用多个字符串/条件对,您可以通过首先列出最不可能匹配的字符串范围/条件来提高性能
。通过重新排序后三个“踢出”Exit For 语句以满足您的
特殊要求,您可能会在特殊情况下看到类似的计算效率提高
但我建议将检查工作表错误作为主要检查。
例如,如果您有很多潜在的字符串匹配项,但可见行很少,则将可见单元格的检查
移到字符串匹配检查上方会减少条件检查。
² 非常感谢Lorem Ipsum Generator 提供示例字符串内容。