How to Count the Number of a Specific Character in a Cell with Excel VBA

前端 未结 6 830
忘掉有多难
忘掉有多难 2021-01-14 22:26

I have a number of items in cells that are separated by dashes. I\'m trying to normalize the database by splitting rows so that each row contains only one entry. How do you

6条回答
  •  北荒
    北荒 (楼主)
    2021-01-14 22:43

    Here's the UDF to count single string occurence in string:

    Option Explicit
    Function COUNTTEXT(ref_value As Range, ref_string As String) As Long
    
    Dim i As Integer, count As Integer
    
    count = 0
    If Len(ref_string) <> 1 Then COUNTTEXT = CVErr(xlErrValue): Exit Function
    For i = 1 To Len(ref_value.value)
        If Mid(ref_value, i, 1) = ref_string Then count = count + 1
    Next
    
    COUNTTEXT = count
    
    End Function
    

    Here's using Array formula:

    =SUM(IF(ISERROR(SEARCH("-",MID(A1,ROW(INDIRECT("$1:$" & LEN(A1))),1))),0,1))
    

    Entered using Ctrl+Shift+Enter.
    Hope this helps.

提交回复
热议问题