计算所选行/单元格中的单词字符

时间:2017-07-06 12:38:33

标签: ms-word character word-vba cells

我必须计算具有表格的单词选择中的字符。我找到了以下VBA代码:

Sub CountCharacters()
    Dim Title As String
    Dim CharCount As Integer
    Dim Message As String

    Title = "CharCount"
    CharCount = Len(Selection)
    Message = LTrim(Str(CharCount)) + " character"
    If CharCount <> 1 Then Message = Message + "s"
    MsgBox Message, vbOKOnly, Title
End Sub

麻烦的是它只统计一个选定单元格的字符。 如何更改它以计算其他单元格中的字符?

谢谢!

1 个答案:

答案 0 :(得分:0)

Option Explicit

Sub CountCharacters()
    Dim Title As String
    Dim CharCount As Integer
    Dim Message As String

    Title = "CharCount"

    'To select the table in which the cursor is place.
    'NOTE: if the cursor is not in a table is will give an error
    Selection.Tables(1).Select

    CharCount = Selection.Range.ComputeStatistics(wdStatisticCharacters)

    Message = LTrim(Str(CharCount)) + " character"
    If CharCount <> 1 Then Message = Message + "s"
    MsgBox Message, vbOKOnly, Title


    'Otherwise you can use:
        'Note that the "Cell End Markers" are seen as two chracters Chr(13) & Chr(7).
        'You will then need to subtract the  number of cells multiplied by 2.
        'You also need to take into account that those cell end markers are in _
            each line outside the table as well.
        'There is also a Selection.Tables(1).Range.Cells.Count but this will omit _
            the additional "Column" of cell end markers
        CharCount = Len(Selection) - (Selection.Tables(1).Rows.Count * _
                                     (Selection.Tables(1).Columns.Count + 1)) * 2

    Message = LTrim(Str(CharCount)) + " character"
    If CharCount <> 1 Then Message = Message + "s"
    MsgBox Message, vbOKOnly, Title

End Sub