2017-07-06 70 views
1

我必須對包含表格的單詞選擇中的字符進行計數。我發現下面的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 

問題是,它只計算一個選定單元格的字符。 如何更改它以計算其他單元格中的字符?

謝謝!

回答

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 
+0

非常感謝你,它的工作原理!解釋也很有幫助。 – LeFunk

+0

@LeFunk,只要記住標記答案是正確的,並給它一個投票。享受Stackoverflow –