vba Word如何在table中获取句子

vba Word how to get sentences in a table

我有一个 Word 文档,前两个句子是普通文本,第三个和第四个句子在 table(在一个单元格中):

My first sentence. My second sentence.

My third sentence. My fourth sentence.

我的代码如下:

Option Explicit
Sub test()
    Dim sentence As Variant
    Dim i As Long: i = 0
    
    Selection.Expand wdSentence
    Debug.Print "--------->" & ActiveDocument.ActiveWindow.Selection.Sentences.Count
    Debug.Print "selection: " & ActiveDocument.ActiveWindow.Selection
    For Each sentence In ActiveDocument.ActiveWindow.Selection.Sentences
        i = i + 1
        Debug.Print i & " sentence: " & sentence
    Next

End Sub

如果我select前两句,调试输出是正确的:

--------->2
selection: My first sentence. My second sentence.


1 sentence: My first sentence. 
2 sentence: My second sentence.

如果我selecttable中的两句,调试输出是奇怪的(或错误的?):

--------->2
selection: My third sentence. My fourth sentence.

1 sentence: My third sentence. 

为什么 table 内容的输出与普通文本不同?我怎样才能使 table 内容获得与普通文本相同的结果?

表格为 Word 识别的句子带来了另一个复杂的维度。段落、单元格结束标记和行结束标记都会导致混淆 VBA.

的句子

这里有一些代码应该可以工作,但我不能 100% 肯定它在所有情况下都可以工作。换句话说,我知道它可以改进,但它应该为您自己的调试会话提供一个良好的开端。

Sub ParseBySentence()
    Dim doc As Word.Document
    Dim i As Long, s As Long, para As Word.Paragraph
    Dim rng As Word.Range, sRng As Word.Range
    
    Application.ScreenUpdating = False
    On Error Resume Next
    Set doc = ActiveDocument
    For i = 1 To doc.Paragraphs.Count
        Set para = doc.Paragraphs(i)
        If para.Range.Information(wdWithInTable) Then
            Set rng = para.Range
            Do While Asc(rng.Characters.Last) = 13
                rng.MoveEnd unit:=wdCharacter, Count:=-1
            Loop
            If rng.Text = vbNullString Or _
                Asc(rng.Text) = 13 Then
                'do nothing
            Else
                For s = 1 To rng.Sentences.Count
                    Set sRng = rng.Sentences(s)
                    Do While Asc(sRng.Characters.Last) = 13
                        sRng.MoveEnd unit:=wdCharacter, Count:=-1
                    Loop
                    sRng.Select
                    Debug.Print Selection.Text
                    Selection.Collapse Word.WdCollapseDirection.wdCollapseEnd
                Next
            End If
        End If
    Next
    Selection.HomeKey unit:=wdStory
    Application.ScreenUpdating = True
    MsgBox "Action Complete"
End Sub

@Rich Michaels:感谢段落提示。我制作了一个快速且简约的宏,它也适用于表格:

Sub Par2Sen()
    Dim s0, s1, smax As Long
    Dim para As Word.Paragraph
    Dim r() As Byte

    For Each para In ActiveDocument.Paragraphs
        r = para.Range
        Debug.Print "> Paragraph= " & para.Range;
        smax = UBound(r) - 1
        s0 = 0
        s1 = 0
        Do Until s1 > smax
            If r(s1) = 46 Or s1 = smax Then
                Debug.Print "-> Sen from" & (s0 / 2) + 1 & " to " & (s1 / 2) + 1 & MidB$(r, s0 + 1, s1 - s0 + 3)
                s0 = s1 + 2
            End If
            s1 = s1 + 2
        Loop
    Next
End Sub