计算范围内的字符a-z

时间:2019-02-15 02:17:12

标签: excel vba

如何通过开发VBA在Excel中的单元格范围内计算字符a-z。例如,我有一个范围为(A1:A10)的名称列表,我需要计算所有范围内的a,b,c,....和z吗?

我尝试使用Chr(64 + i)和InStr进行循环,但是我只得到了使用和不使用的字符,而不是字母总数。

  • 我需要找到每个字符的出现次数,例如a = 20,B = 12,因此。
  • 结果范围没有关系,我们可以将其放在范围B1:C26

1 个答案:

答案 0 :(得分:-3)

范围字符计数

代码

Sub RangeCharactersCount()

    Const cSheet As String = "Sheet1"   ' Source Worksheet Name
    Const cSrc As String = "A1:A10"     ' Source Column Range
    Const cTgt As String = "B1"         ' Target First Cell Range
    Const c1 As Long = 65               ' First Character Code ("A")
    Const c2 As Long = 90               ' Last Character Code  ("Z")

    Dim vntS As Variant   ' Source Array
    Dim vntT As Variant   ' Target Array
    Dim i As Long         ' Source Array Element Counter, Character Counter
    Dim strB As String    ' Concat String
    Dim LenT As Long      ' Current Length

    ' Copy Source Column Range to Source Array.
    vntS = ThisWorkbook.Worksheets(cSheet).Range(cSrc)
    ' Loop through elements of Source Array.
    For i = 1 To UBound(vntS)
        ' Concatenate Concat String and current element of Source Array.
        strB = strB & vntS(i, 1)
    Next

    ' Resize Target Array to number of characters rows and 2 columns.
    ReDim vntT(1 To c2 - c1 + 1, 1 To 2)

    ' Loop through Characters.
    For i = c1 To c2
        ' Write length of Concat String to Current Length.
        LenT = Len(strB)
        ' Replace all occurrences of current letter with empty string ("").
        strB = Replace(strB, Chr(i), "", , , vbTextCompare)
        ' Write current letter to 1st column of Target Array.
        vntT(i - c1 + 1, 1) = Chr(i)
        ' Write number of occurrences (the difference between Current Length
        ' and the length of Concat String) of current letter to 2nd column of
        ' Target Array.
        vntT(i - c1 + 1, 2) = LenT - Len(strB)
    Next

    With ThisWorkbook.Worksheets(cSheet).Range(cTgt)
        ' Clear contents of Target Range (from Target First Cell Range to
        ' last cell of 2nd column).
        .Resize(.Parent.Rows.Count - .Row + 1, 2).ClearContents
        ' Copy Target Array to Target Range.
        .Resize(UBound(vntT), UBound(vntT, 2)) = vntT
    End With

End Sub