COUNTIF/SUMIF 如果条件字符串长于 256 个字符,则会出错

COUNTIF/SUMIF gives error if criteria string is longer than 256 characters

在尝试将 COUNTIF 和 SUMIF 与经常有长注释的 table 一起使用时,我不断收到 #VALUE 错误。一点研究表明错误可能是由于标准字符串超出了 256 个字符点。

关于如何解决这个问题有什么建议吗?我已经制定了一个解决方案,我将作为答案发布,但我想看看是否还有其他人有更好的方法。

我最终在 VB 中编写了一对 UDF 来解决这个问题。仍然有字符限制,但现在是 2^32,而不是 2^8。

COUNTIF 变体非常简单...

    Function COUNTIFLONG(rng As Range, crt As String, ExactMatch As Boolean)

    Dim Cell As Range
    Dim x As Integer

    x = 0

    For Each Cell In rng
        If IsNull(Cell.Value) Then GoTo CellCont
        If ExactMatch Then
          If Cell.Value = crt Then
            x = x + 1
          End If
          Else
            If (InStr(Cell.Value, crt) > 0) Then
              x = x + 1
            End If
        End If
CellCont:
    Next Cell

    COUNTIFLONG = x

End Function

SUMIF 变体要使其足够灵活以供日常使用需要一些技巧。

 Function SUMIFLONG(rngCrt As Range, crt As String, rngSum As Range, ExactMatch As Boolean)

    Dim Cell As Range
    Dim x As Integer
    Dim CrtRows As Integer, CrtCols As Integer, SumRows As Integer, SumCols As Integer
    Dim RowOffset As Integer, ColOffset As Integer
    Dim SumDir As String

    CrtRows = rngCrt.Rows.Count
    CrtCols = rngCrt.Columns.Count
    SumRows = rngSum.Rows.Count
    SumCols = rngSum.Columns.Count

    crt = Trim(crt)

    x = 0

    If (CrtRows <> SumRows) Or (CrtCols <> SumCols) Then
        Debug.Print ("Arrays are not the same size.  Please review the formula.")
        Exit Function
    End If

    If (CrtRows <> 1) And (CrtCols <> 1) And (SumRows <> 1) And (SumCols <> 1) Then
        Debug.Print ("Please restrict arrays to one column or row at a time.")
        Exit Function
    End If

    'Detects the offset of the Sum row/column from the Criteria row/column
    RowOffset = rngSum.Row - rngCrt.Row
    ColOffset = rngSum.Column - rngCrt.Column

    For Each Cell In rngCrt
    'Ignores Null cells or rows where the Sum column's value is not a number.
        If IsNull(Cell.Value) Or (Not IsNumeric(Cell.Offset(RowOffset, ColOffset).Value)) Then
          GoTo CellCont
        End If

    'Adds Sum Column's value to the running total.
    'If an Exact Match is not requested, will detect whether Criteria is present in target cell.
        If ExactMatch Then
          If Cell.Value = crt Then
            x = x + Cell.Offset(RowOffset, ColOffset).Value
          End If
          Else
            If (InStr(Cell.Value, crt) > 0) Then
              x = x + Cell.Offset(RowOffset, ColOffset).Value
            End If
        End If
 CellCont:
    Next Cell

    SUMIFLONG = x

 End Function

正如我所说,我想看看是否有人对如何完成此任务有更好的想法,但我希望这会有所帮助!

如果没有示例数据,任何建议都将涉及一些猜测,但听起来您的搜索条件可以被削减为小于 255 个字符限制的独特部分并用通配符包裹。

=COUNTIF(A:A, "*"&C2&"*")


点击查看大图