计算VBA中每一列的单词数

时间:2019-03-27 10:09:09

标签: excel vba xsl-stylesheet

我正在尝试实现代码,以便可以计算出列中每个单元格的所有单词数,并将其显示在它们旁边的单元格中。

我已经编写了这段代码,但是它显示了Complie Error:没有Do的循环,就在我拥有它的地方。

Sub Command()
    total_words = 1
    Dim ans_length As Integer
    Dim start_point As Integer

    Range("N3").Select

    Do Until ActiveCell.Value = ""

        ans_length = Len(ActiveCell.Offset(0, 13).Value)
        For start_point = 1 To ans_length
            If (Mid(ans_length, start_point, 1)) = " " Then
            total_words = total_words + 1
            End If
        ActiveCell.Offset(0, 12).Value = total_words
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub

说我有这个内容:

      Col1                      Col2
The only way to do multi   |      6
line comments in VB        |      4
the only option you have   |      5
is the single              |      3 

在这里我默认使用col2并为col2编写VBA代码

1 个答案:

答案 0 :(得分:0)

这种UDF方法将是一个更容易的选择……好吧……无论如何,我认为。

Public Function CountWords(ByVal strText As String) As Long
    Application.Volatile
    CountWords = UBound(Split(strText, " ")) + 1
End Function

...您可以在任何单元格中使用它。

enter image description here

如果您想采用原来的方法,那就错过了NEXT。

Sub Command()
    total_words = 1

    Dim ans_length As Integer
    Dim start_point As Integer

    Range("N3").Select

    Do Until ActiveCell.Value = ""
        ans_length = Len(ActiveCell.Offset(0, 13).Value)

        For start_point = 1 To ans_length
            If (Mid(ans_length, start_point, 1)) = " " Then
                total_words = total_words + 1
            End If
        Next start_point

        ActiveCell.Offset(0, 12).Value = total_words
        ActiveCell.Offset(1, 0).Select
    Loop
End Sub