计算 VBA 中每列的单词数

Counting number of words of each column in VBA

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

我已经写了这段代码,但它显示了 Complie Error: Loop without 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 代码

这种 UDF 方法将是一个更简单的选择......好吧......无论如何在我看来。

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

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

如果您想使用原来的方法,则缺少 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