在Excel中的整行内的相同单元格中计算多个值

时间:2017-10-25 21:33:39

标签: excel vba excel-vba

我想创建一个公式来查看excel中的列,并计算是否有条目,例如D48。因此它将通过并计算所有" D48"整个列中的条目,即使它以逗号分隔。所以一个包含" D48,D48"或" D48,D48,D48"将全部计算在内。

我现在有一个工作公式,但它需要空白单元格,并赋值为-1。我怎么能避免这个?有没有更有效的方法来编写这个公式?

Function CountText(sLookFor As String, rSearchRange As Range) As Long

Dim cel As Range

For Each cel In rSearchRange
    CountText = CountText + UBound(Split(cel.Value, sLookFor))
Next cel

End Function

但是这里的代码根据下面的响应而工作(问题解决了!!!)

Function CountText(sLookFor As String, rSearchRange As Range) As Long
    Dim cel As Range

    For Each cel In rSearchRange

    If cel = "" Then

    Else
        CountText = CountText + UBound(Split(cel.Value, sLookFor))
    End If
Next cel

End Function

2 个答案:

答案 0 :(得分:0)

怎么样:

For Each cel In rSearchRange
    if cel = "" then
        next cel
    else
        CountText = CountText + UBound(Split(cel.Value, sLookFor))
    end if
Next cel

For Each cel In rSearchRange
    if cel <> "" then
        CountText = CountText + UBound(Split(cel.Value, sLookFor))
    end if
Next cel

答案 1 :(得分:0)

通过检索字符串的长度减去检索字符串长度而不使用分隔符除以分隔符的长度来跟踪“分隔符”的实例数。

Function CountText(sLookFor As String, rSearchRange As Range) As Long
    Dim cel As Range
    For Each cel In rSearchRange
        CountText = (Len(cel.Value) - Len(Replace(cel.Value, sLookFor, vbNullString))) / Len(sLookFor)
    Next cel
End Function

替换功能目前区分大小写,但可以更改为不区分大小写。