0

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

我已经编写了这段代码,但它显示了 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 代码

4

1 回答 1

0

这种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
于 2019-03-27T10:17:39.920 回答